Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serve react frontend and php backend on same domain with nginx

I have a React frontend and a Symfony backend I'm trying to serve on the same domain. The React frontend needs to serve assets if they exist otherwise fallback to serve index.html.

I'd like to serve the php Symfony app when /api is in the request uri. Similar to the React app, I need all requests to go to the index.php file.

The frontend is being served correctly but not the api. I get a 404 from nginx when i hit /api in the browser.

I feel like i'm close but for some reason nginx doesn't have the correct $document_root. I'm adding a header(X-script) to test what the variables are and I'm getting the following:

X-script: /usr/share/nginx/html/index.php

Here's my nginx config.

server {
    listen 80 default_server;
    index index.html index.htm;

    access_log /var/log/nginx/my-site.com.log;
    error_log /var/log/nginx/my-site.com-error.log error;

    charset utf-8;

    location /api {
        root /var/www/my-site.com/backend;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location / {
        root /var/www/my-site.com/frontend;
        try_files $uri /index.html;
    }
    location ~* \.php$ {
        add_header X-script "$document_root$fastcgi_script_name" always;
        try_files $fastcgi_script_name =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
    }
}

Any help would be much appreciated.

like image 709
David Avatar asked Oct 29 '22 04:10

David


1 Answers

The web root of a Symfony 4 project must include the public subfolder. I am not using NGINX but I think this is the correct configuration:

location /api {
    root /var/www/my-site.com/backend/public;
like image 175
Francesco Abeni Avatar answered Nov 22 '22 21:11

Francesco Abeni