Question

How to redirect https://www.domain to https://non-www for next.js app running on Nginx server

This is what the file looks like. I have tried many things but its won’t work for me


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

        server_name xtremeremoval.com www.xtremeremoval.com;

        location / {
                proxy_pass http://localhost:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/xtremeremoval.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/xtremeremoval.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.xtremeremoval.com) {
       return 301 https://$host$request_uri;
    } # managed by Certbot


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

        listen 80;
        listen [::]:80;

        server_name xtremeremoval.com www.xtremeremoval.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.

Accepted Answer

Hi there,

In your case you have a redirect for www to non-www for HTTP but not for HTTPS.

I had the following problem recently. I’ve used this redirect rule in the 443 server block and it worked:

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

Once you make the change, make sure to run an Nginx config test with nginx -t and then restart Nginx.

Let me know how it goes!

Best,

Bobby