Home  »  CodeGuidesSnippetsTechnologyTools   »   Nginx Redirect www to non-www and non-www to www

Nginx Redirect www to non-www and non-www to www

Posted: March 21, 2022 | by Site Host

Code for Nginx redirect www to non-www with a non-hard coded domain name.

server {
    ...
    # Redirect www to non-www
    if ( $host ~ ^www\.(?<domain>.+) ) {
       rewrite ^/(.*)$ $scheme://$domain/$1;
    }
}

Using hardcoded server_name.

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

server {
    server_name example.com;
    # more configuration options here
}

Example code snippet for non-www to www.

server { 
    if ($host !~ ^www\.) {
        rewrite ^ https://www.$host$request_uri permanent;
    } 
}

Another way: Hardcoded Nginx non-www to www for a single domain.

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

For All Domains:

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

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Share it!

See also  How to Kill Apache Process in Linux