Question

How to redirect all https requests to https www subdomain with Nginx?

I have redirects for http to https working fine. But redirects from https to https does not work. Below is my nginx config file. I would think that the if condition would solve things, but it doesn’t. https://example.com gives the error refused to connect when it should redirect to https://www.example.com. How can I fix this? Note, the ssl cert I’m using does support both www.example.com and example.com. I followed the setup from https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04 if that helps.

server {
       listen 80 default_server;
       listen [::]:80 default_server;
       server_name example.com www.example.com;
       return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl http2 default_server;
        listen [::]:443 ssl http2 default_server;
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name _;
       	 if ($host = "example.com") {
	 	return 301 https://www.example.com$request_uri;
	 }

        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";

        location ~ /.well-known {
                allow all;
        }

        location / {
                try_files $uri $uri/ =404;
        }
}

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

@Tim321

Remove:

if ($host = "example.com") {
    return 301 https://www.example.com$request_uri;
}

Change:

server_name _;

To:

server_name example.com www.example.com;

Then restart NGINX and let me know if that works.

You can use this inside of the server directive.

if ($scheme = http) { rewrite ^/(.*)$ https://example.com/$1 permanent; }

@Tim321

I am stuck in the same space and I am unable to find any answers. Can you please help?

My destination URL is hosted on Amazon AWS.

What worked for you?

Thanks.