nginx – how to rewrite
One of the web servers of the new cloud era is nginx. It's a fast server, with a low memory profile and can handle an impressive amount of concurrent connections compared to a standard apache setup.
It's more than a year since all the servers I work with were switched from apache to nginx. One of the common problem I came across after setting up nginx was figuring out how to do the rewrites. Translating a rewrite rule from apache to nginx is not that hard. The single difference between apache and nginx regarding the regular expression is that apache doesn't take into account the leading slash of the path, so nginx will match ^/the/nice/url for http://example.com/the/nice/url while apache won't.
Next are some common rewrites I came across while working with nginx.
1. Redirect www domain to non-www
if ($host ~* "www.calindon.net") {
rewrite ^/(.*) $scheme://calindon.net/$1 permanent;
}
This redirects with 301 Moved Permanently
2. Redirect to a front controller (eg. WordPress)
if (!-e $request_filename) {
rewrite ^ /index.php last;
}
This will redirect any url that doesn't have a corresponding file to /index.php internally, not affecting the url.
3. Multiple conditions rewrite
One of the problem is that nginx conditional clause (if) doesn't support multiple boolean expressions and neither nested ifs. One can overcome this by using a series of conditions and some boolean rules.
So for example for adding a tailing slash to path of the url you'll have something like:
set $fix_trailing_slash 'yes';
if ($host !~ "^calindon.net$") {
set $fix_trailing_slash 'no';
}
if (-e $request_filename) {
set $fix_trailing_slash 'no';
}
if ($fix_trailing_slash ~* '^yes$') {
rewrite ^/((.*)[^/])$ $scheme://$host/$1/ permanent;
}
4. Mirroring resources, eg. RSS to FeedBurner
set $feed_redirect '';
if ($uri ~ "^/feed/$") {
set $feed_redirect 'http://feeds.feedburner.com/calind';
}
if ($http_user_agent ~* "FeedBurner") {
set $feed_redirect '';
}
if ($feed_redirect ~* "^(.+)$") {
rewrite ^ $feed_redirect? permanent;
}
This will redirect http://calindon.net/feed/ to FeedBurner, but will allow FeedBurner to get the content out of the url and mirror it.
More about this topic can be found on nginx's rewrite documentation page.