Cloudflare + Nginx + Certbot: Redirect isn't working from non-www to www

I am super new to Nginx and CF and I have deployed my website to example.com and it is working perfectly and it redirects to https as well. But I want to redirect to www all the time. Right now if I type in example.com it doesn’t redirect to www.

This is one of the million solutions I tried where I added www.example.com in the return statement:

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

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

}

But it isn’t working. What is wrong here?

Here’s the full nginx config for the website:

server {

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.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_set_header X-Real-IP $http_cf_connecting_ip;
        proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_cache_bypass $http_upgrade;
    }

    real_ip_header CF-Connecting-IP;

}

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

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

}

I have enabled Development Mode in CF, tried a million things, asked in Reddit, StackOverflow and ServerFault, none seems to be working. Someone please help me.

Save yourself the hassle of doing it on the server and get Cloudflare Page Rules to do it for you. It’ll be way faster and more reliable too, since your server doesn’t have to handle anything to do with redirects.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.