Nginx Config for Laravel + WordPress Hybrid Apps

πŸ“– 2 minutes read

Running Laravel as an API backend alongside WordPress on the same server? Here’s how to configure Nginx to route /api/* requests to Laravel while serving everything else through WordPress.

This pattern is useful when you want Laravel’s powerful API capabilities but need WordPress for content management.

The Nginx Configuration

server {
    listen 80;
    server_name app.example.com;
    
    # Default to WordPress
    root /var/www/wordpress;
    index index.php index.html;

    # Route /api/* to Laravel
    location ~ ^/api {
        root /var/www/laravel/public;
        try_files $uri $uri/ /index.php?$query_string;
        
        location ~ \.php$ {
            fastcgi_pass php:9000;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root/index.php;
            fastcgi_param SCRIPT_NAME /index.php;
        }
    }

    # WordPress permalinks
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # PHP handler for WordPress
    location ~ \.php$ {
        fastcgi_pass php:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

How It Works

The key is location priority. Nginx processes locations in this order:

  1. Exact matches (=)
  2. Prefix matches with ^~
  3. Regex matches (processed in order)
  4. Prefix matches

The ~ ^/api regex catches API routes first, switches the root to Laravel’s public directory, and passes PHP requests to Laravel’s front controller.

Everything else falls through to the default root (WordPress) and uses WordPress’s permalink handling.

Why This Pattern?

You might need this when:

  • Migrating from WordPress to Laravel incrementally
  • Building a mobile app that needs clean REST APIs but wants to keep WordPress for the marketing site
  • Your team knows WordPress for content but prefers Laravel for backend logic

The hybrid setup lets each framework do what it does best without migration pressure.

Gotcha: Don’t forget to change the root directive inside the /api location block. If you only set try_files without changing root, Nginx will look for Laravel files in the WordPress directory.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *