Nginx 403 when serving static files + reverse proxy

http-status-code-403nginxreverse-proxystatic-files

I'm trying to serve a node app through nginx, but first attempt to serve static files that may be in a /public folder. I've got that much working — but when accessing domain.tld/ or the index of static folders, I get a 403; directory index of "/var/www/domain.tld/" is forbidden. All the permissions seem to correct, so I'm rather confused.

This is my server block;

server {
    server_name domain.tld;

    location / {
        root /var/www/domain.tld/public;
        try_files $uri $uri/ @proxy;
        access_log off;
    }

    location @proxy {
        proxy_pass http://127.0.0.1:3000;
    }
 }

Accessing any random page (including assumed sub-directories) properly proxies to the node app. In the case of the root / and root of any existing static directory, however, 403.

Any ideas?

Best Answer

That's because the directory exists, and therefore the try_files check

try_files $uri $uri/ @proxy;

succeeds. But there is no directory index file (typically index.html, see index), and autoindex is not turned on either (see autoindex).

Depending on what you want to happen, consider the following options:

  • Leave it as is (and may be tune which index files are used).
  • Always pass directories to a backend. Remove $uri/ from try_files to do it, i.e.:

    location /
        root /var/www/domain.tld/public;
        try_files $uri @proxy;
    }
    
  • Check for a particular index file via try_files (and the request will go to a backend if it's not found):

    location /
        root /var/www/domain.tld/public;
        try_files $uri $uri/index.html @proxy;
    }
    
  • Enable autoindex:

    location /
        root /var/www/domain.tld/public;
        try_files $uri $uri/ @proxy;
        autoindex on;
    }