Redirecing all Nginx traffic to a canonical subdomain

December 01, 2014

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.

Join the Mailing List

Subscribe to get weekly updates and my latest articles by email.

    (About the content, privacy, analytics and revocation).

    We won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit