Configuring nginx for Laravel backend with React frontend

I’m seeking assistance with setting up nginx to host a React application as the frontend alongside a Laravel backend handling specific API and admin routes. While React manages most paths, I need nginx to direct requests for /api and /admin to the Laravel application.

Currently, I’m encountering issues where accessing these routes leads to errors like “file not found” or a blank page. I’ve already attempted to reinstall nginx and re-clone both projects, and I’ve verified that php-fpm is running properly.

Below is my nginx configuration:

server {
    listen 80;
    server_name mydomain.com;
    client_max_body_size 100M;

    location / {
        root /var/www/html/react/dist;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/(api|admin) {
        root /var/www/html/app/public;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
        fastcgi_read_timeout 300;
    }

    location ~ /\.(ht|env) {
        deny all;
    }
}

What might I be overlooking in this setup? Any advice would be greatly appreciated.

there’s also a fastcgi_param issue - when nginx rewrites to /index.php for laravel routes, SCRIPT_FILENAME won’t resolve right because you’re switching root directories. try using alias instead of root in your api/admin block, or just set fastcgi_param explicitly to /var/www/html/app/public/index.php for those routes.

what error logs are you getting in nginx or php-fpm? that’d help figure out what’s breaking when requests hit those routes. also - does the laravel app work fine with php artisan serve? worth checking if it’s an nginx config issue or something in laravel itself.

Your PHP location block is the problem. The location ~ \.php$ block uses $document_root, which points to your main location’s root (/var/www/html/react/dist) instead of your Laravel app path. So when nginx processes /api/some-endpoint, it matches your API location fine, but if the request gets rewritten to /index.php, the PHP handler looks in the React directory instead of Laravel’s public folder. You’ve got two options: add root /var/www/html/app/public; inside your location ~ \.php$ block, or nest the PHP location block within your API/admin location block. I’d go with the second approach - it’s cleaner for path resolution. This kind of config mismatch happens all the time when you’re serving multiple apps from one nginx server block.