NGINX: rewrite non-www to www for multi domain virtual hosts

If you have NGINX virtual host that has a multi different domains pointing to same document root (multi server_name), and you want to automatically redirect non-www to www, than bellow is simple solution. I also wanted to redirect to https with www.

If you don’t need https redirection, than you can simply use variable $scheme instead of “https:”. 

if ( $host !~ ^www\. ) {
            return 302 https://www.$host$request_uri;
}

So virtual host should look something like this:

server {
      listen 1.1.1.1:80;
      server_name domain1.com www.domain1.com domain2.com www.domain2.com;

      if ( $host !~ ^www\. ) {
           return 302 https://www.$host$request_uri;
      }
      return 302 https://$host$request_uri;
}

You should also make this redirect in your https server definition. otherwise request for https://domain1.com won’t redirect to www.

server {
      listen 1.1.1.1:443;
      server_name domain1.com www.domain1.com domain2.com www.domain2.com;
      if ( $host !~ ^www\. ) {
              return 302 https://www.$host$request_uri;
      }

      ssl on;
      ssl_certificate /etc/letsencrypt/live/domains.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/domains.com/privkey.pem;

      .... //other nginx configuration ....
}

© 2024 geegkytuts.net
Hosted by SIEL


About author