Nginx — static file serving confusion with root & alias

There is a very important difference between the root and the alias directives. This difference exists in the way the path specified in the root or the alias is processed.

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

To illustrate…

Let’s say we have the config

        location /static/ {
                root /var/www/app/static/;
                autoindex off;
        }

In this case the final path that Nginx will derive will be

/var/www/app/static/static

This is going to return 404 since there is no static/ within static/

This is because the location part is appended to the path specified in the root. Hence, with root, the correct way is

        location /static/ {
                root /var/www/app/;
                autoindex off;
        }

On the other hand, with alias, the location part gets dropped. So for the config

        location /static/ {
                alias /var/www/app/static/;
                autoindex off;
        }

the final path will correctly be formed as

/var/www/app/static

See the documentation here: http://wiki.nginx.org/HttpCoreModule#alias

 

References:

http://stackoverflow.com/questions/10631933/nginx-static-file-serving-confusion-with-root-alias

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s