Nginx serve static files AND reverse proxy

nginxPROXYreverse-proxystatic-files

I want the browser to be in constant communication (websocket) with my backend servers as they are constantly receiving data. But I also want static files to be served to them by nginx. In other words, I want nginx to serve static files AND ALSO proxy to my backend servers. I've tried putting both directives in the same location block:

location / {

        # SERVE STATIC FILES:
        root C:blah/blah/blah;
        index mysite.html;

        # ANDDDD REVERSE PROXY TO BACKEND SERVERS:
        proxy_pass https://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400;
}

.. but this just skips the serving of static files and goes straight to my backend servers.

I've also tried:

location / {

# SERVE STATIC FILES:
root C:blah/blah/blah;
index mysite.html;
try_files $uri $uri/ @proxy;

}

location @proxy {

# ANDDDD REVERSE PROXY TO BACKEND SERVERS:
proxy_pass https://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;

}

.. but of course this just serves the static files and does not proceed with the proxy since the mysite.html was found.

I've also tried:

location / {

# SERVE STATIC FILES:
root C:blah/blah/blah;
index mysite.html;

}

location / {

# ANDDDD REVERSE PROXY TO BACKEND SERVERS:
proxy_pass https://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;

}

.. but this produces an error as there are now two location / blocks.

Does anyone know how to make nginx serve static files AND proxy to a backend server?

Best Answer

index mysite.html directive makes nginx server mysite.html to all requests that end with /.

If you want to only serve files from backend when a static file is not found, you need to have:

location / {
    # SERVE STATIC FILES:
    root C:blah/blah/blah;
    try_files $uri $uri/ @proxy;
}

location @proxy {
    # ANDDDD REVERSE PROXY TO BACKEND SERVERS:
    proxy_pass https://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;
}