Search code examples
webnginxnginx-reverse-proxyno-www

Nginx redirect everything to www https


I want to redirect everything to https://www

This is my config block where I tried redirecting non www to https but does not work.

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

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

server {
    listen 443 ssl;

    location /auth {
        ...
    }

    location / {
       ...
    }

    ssl_certificate /root/certs/fullchain.pem;
    ssl_certificate_key /root/certs/privkey.pem;

}

http://example.com gives 404 error

https://example.com does not redirect to https://www

http://www.example.com redirects to https://www

https://www.example works as is


Solution

  • server {
        listen 80;
        server_name example.com www.example.com
        return 301 https://www.example.com$request_uri;
    }
    
    server {
        listen 443 ssl;
        server_name example.com 
        ssl_certificate Certificate/For/example.com/fullchain
        ssl_certificate_key Key/For/example.com/ 
        return 301 https://www.example.com$request_uri;
    }
    
    server {
        listen 443;
        server_name  www.example.com
        ssl_certificate Certificate/For/www.example.com/fullchain
        ssl_certificate_key Key/For/www.example.com/key
    
        //do whatever you want with your https://www.example.com connection
    
    }   
    

    Remember to have both certificates, one for www and one without, as if you redirect example to www without certificate, that's a non-secure step, and an error will show.

    Hope I helped