Question

Not automatically redirect to HTTPS

I have been following the NGINX SSL with Let’s Encrypt tutorial and appear to have successfully configured SSL for my server, but it doesn’t appear to default to that. When I access my website with www.domain.com it defaults to http and 404 result, but if I use https://www.domain.com, I am able to access the website

Here is my /etc/nginx/sites-available/domain.com config

server {

        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;

        server_name domain.com www.domain.com;

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

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}
server {
    if ($host = www.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




}


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.

Hello,

I could suggest changing your server block for port 80 to the following:

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

That way all requests on port 80 would go to https.

Make sure to run nginx -t after the changes and before restarting nginx.

Regards, Bobby