Redirecing all Nginx traffic to a canonical subdomain

December 1, 2014 [ nginx ]

On this site, I redirect all undirected trafic to the blog subdomain. This happens with the following Nginx configuration snippet:

server {
    listen      80;
    server_name th4t.net;
    #rewrite ^/(.*) http://blog.th4t.net/$1 redirect;
    return  301 http://blog.th4t.net$request_uri;

Any request aimed at the th4t.net domain which is not caught by a more specific rule, is redirected to a corresponding blog.th4t.net url. The commented-out rewrite is what one would want to use coming from an Apache background. When working with Nginx, rewrites are discouraged. Thus, the redirect via return code is the way to go. The 301 response code can be decoded as Moved Permanently. It was motivated by the goal to get rid of ambiguous links to the same content and redirect them to a single subdomain. If the goal were to catch undirected traffic, a 307 code might be more appropriate.

Want to be notified when I publish new content?

Just enter your name and email below. You will also get content that I share exclusively with the list, and zero spam!