Nginx Only Works Sometimes

The other day I implemented a fairly common nginx rewrite rule which moved all www.domain.com traffic to domain.com.

The code was:

server { listen 80; server_name www.domain.com; rewrite ^(.*)$ $scheme://domain.com$1; }

The thing is, it only worked some of the time. It seemed to be random, from some computers it worked and from others it did not. At one point it seemed that the front page of the domain would redirect, but no other page would.

The solution was one that is getting to be more and more common these days, especially with DNS. I had setup an IPv4 rule but not an IPv6 rule, while the other servers in my nginx configuration did have IPv6 and Ipv4 rules.

When connecting over IPv4 the server redirected just fine. When connecting over IPv6 on the other hand, the server would not redirect because it is not instructed to listen in on IPv6.

The solution was to add an IPv6 rule into the above. The final redirect configuration looks like this:

server { listen 80; listen [::]:80; server_name www.domain.com; rewrite ^(.*)$ $scheme://domain.com$1; }