Search code examples
nginxnginx-locationnginx-config

Serving react frontend and flask backend simultaneously (nginx)


I have a react frontend and a flask backend.

Currently I serve backend the following way

server {
    location / {
        try_files $uri @yourapplication;
    }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }
}

I'd like to configure nginx in a way that would allow me to serve my react app from / and access API from all other routes (i.e. /users is an api endpoint).

Is it a "sensible" set up? What should my config file look like?


Solution

  • Ended up using the following setup

    server {
    
        root /var/www;
        index index.html index.htm;
    
        location =/ {
            try_files $uri $uri/ /index.html;
        }
    
        # Media: images, icons, video, audio, HTC
        location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
            expires 1M;
            access_log off;
            add_header Cache-Control "public";
        }
    
        # Javascript and CSS files
        location ~* \.(?:css|js)$ {
            try_files $uri =404;
            expires 1y;
            access_log off;
            add_header Cache-Control "public";
        }
    
        # Any route containing a file extension (e.g. /devicesfile.js)
        location ~ ^.+\..+$ {
            try_files $uri =404;
        }
    
        location /user {
            try_files $uri @yourapplication;
        }
    
        location /register {
            try_files $uri @yourapplication;
        }
    
        location /login {
            try_files $uri @yourapplication;
        }
    
        location @yourapplication {
            include uwsgi_params;
            uwsgi_pass unix:///tmp/uwsgi.sock;
        }
    }
    

    In other words, for production it serves static files on =/ and for every other end ponint passes it to flask.