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.

About Ricky1990

I'm Ricky, a programmer. My interests are Marketing Online, Wordpress, SEO, Make Money Online and Software. Besides computers, i am crazy for bussiness projects, web development consulting and work as a speaker about these fields.

Speak Your Mind

*