Nginx alias vs root directives. Nginx serves static files. Trailing slash in path

Nginx alias vs root directives. Nginx serves static files. Trailing slash in path

Sample nginx.conf

events { worker_connections 1024; }
http {
  server {
    listen 80;

    location /a {
      root /www; # root without trailing slash
    }
    location /b {
      root /www/; # root with trailing slash
    }
    location /c {
      alias /www; # alias without trailing slash
    }
    location /d {
      alias /www/; # alias with trailing slash
    }
  }
}

These are requests and file path that nginx will look up for

https://example.com/a/my/file -> /www/a/my/file
https://example.com/b/my/file -> /www/b/my/file
https://example.com/c/my/file -> /wwwmy/file
https://example.com/d/my/file -> /www/my/file

Check this article to reveal the location that nginx looks up for

Also note that, from nginx official docs, it is recommend to use root directive when possible.


When location matches the last part of the directive’s value:

location /images/ {     alias /data/w3/images/; }

it is better to use the root directive instead:

location /images/ {     root /data/w3; }

The reason is a little performance of root over alias when matching request string