Question

Issue with non www and www redirect to www with https in Nginx

I am Trying to redirect all my urls both with www and without www to single url. Example: http://example.com -> https://www.example.com (Redirecting With 301 OK) http://www.example.com -> https://www.example.com (Redirecting With 301 OK) https://example.com -> https://example.com (Not Redirecting) https://www.example.com -> https://www.example.com (Not Redirecting)

My Current Config Look Like

server {
    server_name www.example.com example.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/myloc/mydir;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.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.example.com) {
        return 301 https://www.example.com$request_uri;
    } # managed by Certbot


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


    listen 80;
    server_name www.example.com example.com;
    return 404; # managed by Certbot


}

PLease help


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.

Remove example.com from server_name directive and create a new server block

server {
        listen 443;
        listen [::]:443 ipv6only=on;
        server_name example.com;
        ssl_certificate ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        return 301 https://www.example.com$request_uri;

}