Perm Redirect to Non-WWW Not Working

Please fill out the fields below so we can help you better. Note: you must provide your domain name to get help. Domain names for issued certificates are all made public in Certificate Transparency logs (e.g. crt.sh | example.com), so withholding your domain name here does not increase secrecy, but only makes it harder for us to provide help.

My domain is:

I ran this command:

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


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



        server_name pcnselect.com www.pcnselect.com;
    listen 80;
    listen [::]:80;
    return 301 https://pcnselect.com$request_uri;
}

It produced this output:
I expect requests to www.pcnselect.com to permanently redirect to pcnselect.com - they don;t and I don;t understand why not based on the server block Certbot injects.

My web server is (include version):
nginx/1.25.0

The operating system my web server runs on is (include version):
Ubuntu 18.04.6 LTS

My hosting provider, if applicable, is:

I can login to a root shell on my machine (yes or no, or I don't know):
yes

I'm using a control panel to manage my site (no, or provide the name and version of the control panel):
no

The version of my client is (e.g. output of certbot --version or certbot-auto --version if you're using Certbot):
certbot 4.0.0

It seems to be redirecting just fine from my point of view?

1 Like

Really? Maybe I'm behind some aggressive caching, but I remoted into a machine on another network and going to www.pcnselect.com does not redirect to https://pcnselect.com there either - you're saying it does for you?

Yes, it does. See for yourself using e.g. Redirect Checker | Check your Statuscode 301 vs 302

2 Likes

If I use that tool, http:// redirects correctly, but https://www.pcnselect.com does not - do I need to add:

listen 443 ssl;
listen [::]:443 ssl;

to that server block, or duplicate the $host checking logic in my other SSL server block?

If you want to redirect the HTTPS request you need a redirect in the server block handling port 443. There are various ways to do this. But, adding below to the port 443 server block is probably easiest:

if ($host = www.pcnselect.com) {
        return 301 https://pcnselect.com$request_uri;
 }

No, definitely do not do that. While technically possible it is hardly ever easier and often makes certain things very difficult to configure.

You should already have a server block that has those two listen statements for those two server_names. Put the above if statement in that.

5 Likes

Thank you very much, makes sense and works for me.

2 Likes