nginx redirect – How to Redirect All Domains to www Subdomain in Nginx

nginxredirect

I have an nginx config that works as intended for one of my domains but there is a weird redirecting behaviour whenever I point another domain to my server.

Issue:
I want to redirect all request made to any non-www to the www version of my site.

Eg:
http://example.com should redirect to https://www.example.com
http://m.example.com should redirect to https://www.example.com

My config works as intended for example.com but whenever I cname, say cdn.test.com to my server ip with a separate config file. It redirects to www.cdn.test.com

This is my config for example.com:

    server{
        #redirect non-www to www
        listen 80;
        listen 443 ssl;
        server_name example.com;

        ssl_certificate .../cert.pem;
        ssl_certificate_key .../key.pem;   
        return 301 https://www.$host$request_uri;
    }


    server{
        #redirect request to the mobile site to the main site
        listen 80;
        server_name m.example.com;
        return 301 https://www.example.com$request_uri;
    }
    server{
        #redirect unsecure www to secure wwww
        listen 80;
        server_name www.example.com;
        return 301 https://$host$request_uri;
    }
    upstream backend {
        server 127.0.0.1:23042;
        server 127.0.0.1:23043 backup;   
     }
    server {
        listen 443 ssl;
        server_name www.example.com;

        access_log off;
        error_log off;

        ssl_certificate .../cert.pem;
        ssl_certificate_key .../key.pem;   

        location / {
            proxy_pass http://backend;
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header CF-IPCountry $http_cf_ipcountry;
        }

        location /static {
            alias .../app/static;
            expires 30d;
        }
    }

and this is the config for cdn.test.com:

    server {
      listen 80;
      server_name cdn.test.com;
       root /home/.../files;
    }

Best Answer

In your config first server block is the default_server which will be used for all requests that don't match a more specific server.

Rather than return 301 https://www.$host$request_uri; in the default_server don't use the Host header from the request as a parameter to generate the redirect, as that can become all kinds of incorrect things, instead use return 301 https://www.example.com$request_uri; to always redirect to www.example.com