Question

Not automatically redirect to HTTPS

Posted November 23, 2019 1.4k views
Nginx

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




}

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

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

Submit an Answer