nginx 301 redirect does not work for www. subdomain

Brian asked:

I am attempting to create a 301 re-direct from one domain to another with nginx. Here is what I’m currently doing and it works as I want:

   server {
        listen      80;
        server_name domain.net;
        return 301 $scheme://www.domain.net$request_uri;
    }

    server {
            listen       80;
            server_name  www.domain.net;
            ...
    }

I’d like to modify the first server block to include a .co domain to also re-direct to www.domain.net:

   server {
        listen      80;
        server_name domain.net domain.co www.domain.co;
        return 301 $scheme://www.domain.net$request_uri;
    }

However, when I type in www.domain.co, the site loads fine, but the address bar still shows www.domain.co instead of www.domain.net. Likewise, doing a curl -I www.domain.co shows a 200 instead of a 301. Omitting the www. and only typing domain.co sends me to www.domain.net. curl -I domain.co also returns a correct 301.

Any idea why this is not working when I add the www.? I’ve been trying for some time now and searching/trial-and-error have come up fruitless.

My answer:


Your nginx rewrite rules look fine.

The most likely cause of this issue is that your DNS records aren’t yet up to date. Double check to ensure that you’ve pointed the DNS A records for domain.co and www.domain.co to the right address. If you’ve recently updated the DNS records, it may take additional time before the updates are propagated and the old records expire. This is reflected in the Time-To-Live (TTL) value in your DNS SOA record.

Finally, if you’ve updated your nginx configuration, you also need to reload/restart nginx.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.