nginx root vs alias

kiran
2 min readApr 8, 2021

--

Suppose you want to serve a file welcome.html, we can achieve using either alias or root directives as below with some differences.

a) Lets assume your website files are at

Web Files Path: /data/pages

alias

location /pages/ {
alias /data/pages/;
}

So the file will be served from /data/pages/welcome.html

Request: /data/pages/welcome.html
File served from /data/pages/welcome.html

root

As the request path excluding the actual file matches the location directive, in this case its better to use root directive as below

location /pages/ {
root /data;
}

Request: /data/pages/welcome.html
File served from /data/pages/welcome.html

So root directive appends the location path to it and searches for the file in /data/pages for welcome.html

s used when the path matches the directory hierarchy where the file is present.

b)

Web Files Path: /data/content/page

alias

location /pages/ {
alias /data/content/page/;
}

Request: /data/pages/welcome.html
File served from /data/content/page/welcome.html

root

As the request path excluding the actual file does not matche the location directive, in this case alias was a better choice.We can still achieve the same with root by rewriting the url

location /pages/(*.html) {
root /data/content;
rewrite .* /page/$1 break;
}

Request: /data/pages/welcome.html
File served from /data/content/page/welcome.html

When alias is used a regex location block, the alias should be full path to the file and should include the captures from the location.

https://stackoverflow.com/questions/53279886/nginx-alias-path-based-on-regex

--

--

kiran
kiran

Written by kiran

I am a software engineer by profession. I write so as to remind my selves when I forget :-)

No responses yet