Question

Unnecessary redirects for HTTPS

Posted February 3, 2016 4.3k views
Nginx DNS

My recently configured droplets are exhibiting some unnecessary redirects and I cannot figure out why.

End result should https://domain.com

So I need to rewrite www requests and non-https requests to https without the www.

Currently the opposite is happening, and adding an extra redirect which is costing about an extra 1 second.

So domain.com (307) -> https://domain.com (301) -> https://www.domain.com (200)

My NGINX server blocks looks like this:

server {
servername domain.com www.domain.com;
return 301 https://$server
name$request_uri;
}

server {
listen 443 ssl;

    ssl_certificate /path/to/fullchain.pem;
    ssl_certificate_key /path/to/privkey.pem;

    root /path/to/html;
    index index.php;

    server_name domain.com www.domain.com;

    #additional configurations

}

Some additional information:

  • SSL cert is for both non-www and www
  • A name pointing to IP, with WWW CNAME pointing to domain.com.
  • Total of 3 sites with the same configuration. Only 1 redirects properly. Incidentally it’s also the only site not currently pointing to Cloudflare DNS. I suspect this might be the source of my issues.

Any help would be greatly appreciated. This is the last roadblock to sub-second load times.

4 comments

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

1 answer

Try:

server {
    #Redirecting to SSL site
    listen 80;
    listen [::]:80 ipv6only=on;
    server_name domain.com;

    location / {
      return              301 https://$server_name$request_uri;
    }
}

Try removing the additional www.domain.com under listen. If that doesn’t work and redirects don’t work from www.domain.com, add an additional block just for www.

Submit an Answer