Nginx Configuration for PHP Laravel & ReactJS in Single Site
-
Laravel + ReactJS is a super common combination and getting it working right under an Nginx front end can be confusing. Here is a quick config to copy!
server { listen 80; listen [::]:80; server_name app.myserver.com; # ---- React SPA ---- location / { root /var/www/myapp/myfrontend/dist; index index.html; try_files $uri /index.html; } add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; # ---- Map /api/* to Laravel public ---- location ^~ /api/ { root /var/www/myapp/myapi/public/; index index.php; try_files $uri $uri/ /index.php?$query_string; } # ---- PHP under /api/* (MUST use fastcgi.conf, not the snippet) ---- #location ~ ^/api/.+\.php$ { location ~ \.php$ { root /var/www/myapp/myapi/public/; # Split PATH_INFO (rarely needed by Laravel, but safe) fastcgi_split_path_info ^/api/(.+\.php)(/.*)$; include fastcgi.conf; # <-- NOT snippets/fastcgi-php.conf fastcgi_pass unix:/run/php/php8.4-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } # Block dotfiles anywhere (SPA + API) location ~ /\. { deny all; } }
-
Some assumptions here. First, only configured for port 80, make sure you address TLS somehow (another proxy in front of this or add config here.)
You have a single folder /var/www/myapp in which you have myfrontend containing your ReactJS application and myapi that contains your Laravel application.
Tested with Nginx on Linux.