Nginx Locations and Redirects
Locations
Locations are a way to link a URL to a specific file in your filesystem.
Multiple locations can be set per server and Nginx will use the rule with the longest match.
Consider the following:
server { listen 80; server_name spmbook.com; location / { root html/spmbook; index index.html index.htm; } location /course { alias html/spm; index index.html index.htm; } }
tells Nginx to serve all content of spmbook.com
from the directory
html/spmbook
, with the exception of any URL containing /course
,
which will be taken from the html/spm
directory.
Thus, for instance:
URL | File in the file system |
---|---|
http://spmbook.com/2014/index.html |
html/spmbook/2014/index.html |
http://spmbook.com/course/2014/index.html |
html/spm/2014/index.html |
Using multiple locations is useful, for instance, if you publish different websites under the same domain.
In my case, for instance, the html sources of spmbook.com and spmbook.com/course/2014 live in two different Jekyll repositories: using different locations I can publish one independently from the other, while presenting them as belonging to the same domain.
Rewrite Rules
Nginx rewrite rules specify how URLs have to be redirected.
This is useful when you make changes to your web content which break URLs external sites might still reference, like, for instance, when you move or delete some posts.
Consider, for instance, the following rewrite
directive:
server { ... server_name ict4g.net www.ict4g.net; ... rewrite "/adolfo/spm[0-9]{2}.*$" http://www.spmbook.com/redirected.html; }
Here, the rewrite
rule redirects URLs in the form
http://ict4g.net/adolfo/spm[0-9][0-9]/...
to
http://www.spmbook.com/redirected.html.
This is the rule I use to redirect students trying to access old
editions of my Software Project Management course (which used to be
published in my home, under spm<YEAR>
) to the new dedicated website
which hosts all the content related to the course.