Question

I want to redirect http://www.example.com, https://www.example.com, http://example.com to https://example.com


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.

Hi there,

I recently answered a similar question here:

https://www.digitalocean.com/community/questions/how-to-redirect-https-www-domain-to-https-non-www-for-next-js-app-running-on-nginx-server

What you could do is first setup your HTTP to HTTPS redirect:

server {
    if ($host = www.domain.com) {
       return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name domain.com www.domain.com;
    return 404; # managed by Certbot
}

And then setup the HTTPS redirect from the www to the non-www version:

    if ($host ~ ^www\.(?<domain>.+)$) {
        return  301 $scheme://$domain$request_uri;
    }

Best,

Bobby