Configure Nginx redirect www to non-www and vice versa

There are many ways to force Nginx using url has www or non-www. I would like to introduce a simple way follows:

Redirect non-WWW to WWW

Edit nginx configuration file (/etc/nginx/nginx.conf):

Single domain

server {
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;
}

All domains

server {
        server_name "~^(?!www\.).*" ;
        return 301 $scheme://www.$host$request_uri;
}

From WWW to non-WWW

Single domain

server {
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
}

All domains

server {
         server_name "~^www\.(.*)$" ;
         return 301 $scheme://$1$request_uri ;
}

In addition, there are some WordPress plugins that can handle this redirect in the PHP-level, but to have the best performance, you should let Nginx handle themselves.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz