Nginx: useful configuration directives
Nginx: useful configuration directives
This article will function along the lines of a Tips and tricks-style article, where I'll be showing off various configuration directives for nginx to use in the wild to achieve specific purposes.
Hopefully, this article will grow over time.
Mapping a specific URL location to a directory location on the system
Sometimes, you may want a very simple configuration where you have a specific URL location (i.e. https://pentilescu.com/bin/**) and you want this URL prefix to indicate to Nginx to use a specific directory on the system to look for the requested files in. Or, in other words, every HTTP GET request sent to https://pentilescu.com/bin/** (e.g. https://pentilescu.com/bin/folder1/myfile.png**) to be searched for in a specific systems directory (e.g. /var/www/static/). This way, a request for https://pentilescu.com/bin/folder1/myfile.png** should resolve to /var/www/static/folder1/myfile.png. How do we do this?
Simple! We use the "alias" directive, like so!
server_name pentilescu.com;
location /robots.txt {
alias /var/www/static/robots.txt;
}
location /sitemap.xml {
alias /var/www/static/sitemap.xml;
}
location /bin/ {
alias /var/www/static/;
}
location / {
return 301 https://alexandru.pentilescu.com$request_uri;
}
listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443;
}
Please note that the most important part of that snippet is the location /bin/ directive, followed by the alias, which tells nginx to map all GET requests sent to the /bin/ URL to the /var/www/static directory.
The other directories above it (i.e. the location /robots.txt directive) also use the alias directive, but they use it to map to a specific file location, rather than a directory location. This is also possible.