April 7th, 2010
Clean parameter based Nginx re-writes with map
When I migrated to my new blog, I needed to re-write all the old WordPress URLs to point to the appropriate place. The problem was that standard rewrites aren’t made based on GET parameters, so I was stuck.
Luckily Curly060 and Seph in #nginx gave me some ideas, and together we ended up with this:
# Put this outside of server stanza
map $arg_cat $category {
6 /blog/topic/security;
11 /blog/topic/mac;
8.* /blog/topic/lisp;
9.* /blog/topic/code;
3 /blog/topic/linux;
14 /blog/topic/thoughts;
10 /blog/topic/php;
7 /blog/topic/security;
12 /blog/topic/emacs;
5 /blog/topic/projects;
9 /blog/topic/code;
13 /blog/topic/python;
1 /blog;
8 /blog/topic/lisp;
}
# Put this with other re-writes
if ($category) {
rewrite ^ $category;
}
If you want to do a permanent redirect, you have to clear all the arguments to prevent a redirect loop. The last stanza would look something like this:
if ($category) {
set $args "";
rewrite ^ $category permanent;
}