*24 Jan 2015*
<div class="posthaven-post-body">
When i moved my blog to a \[middleman\](http://middlemanapp.com) system, i found that i needed to provide redirects from \`/2012/01/25/some-post\` to \`/blog/2012/01/25/some-post\`. It's a relatively simple task, though i lost some time because i missed a detail that no one usually explains.
There are articles on the web explaining how to do url rewriting in Nginx. Most of them will tell you something like this:
location /2009/ { rewrite ^(/2009/.\*)\$ /blog\$1 break; }
In a gist, that's what you need. What they forget to mention is it will not work unless you provide the \*root\* in that \*location\* block.
Another thing you might want to do, to track eventual problems with your regular expression skills (hehe), is activate rewrite logging. It's also a good idea to inform clients that the resource moved permanently (301).
The full solution ended up being:
server { listen 80; server_name pedroassuncao.com \*.pedroassuncao.com;
access_log /path/to/your/logs/nginx.access.log; error_log /path/to/your/logs/nginx.error.log;
rewrite_log on;
location /2009/ { root /path/to/your/html/; rewrite ^(/2009/.\*)\$ /blog\$1 break; return 301; }
location / { root /path/to/your/html/; expires 24h; }
error_page 404 /404; }
A final note: When you activate \`rewrite_log on;\` nginx will dump all rewrite information to your \*error\* log as a notice. Since notice is the default it will show up. You can always make sure, by adding \*notice\* after the log file:
error_log /path/to/your/logs/nginx.error.log notice;
Happy nginxing :)
</div>
[[tags/301|301]] [[tags/help|help]] [[tags/nginx|nginx]] [[tags/redirect|redirect]] [[tags/rewrite|rewrite]] [[tags/tips|tips]]