Nginx redirect no-www to www and www to no-www

You can configure nginx to return http://example.com instead of http://www.example.com and vice versa. This setting is important because you want your want your visitors to both access your website via www an no-www.

Nginx redirect www to no-www

server {
    #listen 80 is default
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    #listen 80 is default
    server_name example.com;
    ## here goes the rest of your conf...
}

This configuration will redirect all www requests to no-www requests.

 Nginx redirect no-www to www

server {
    #listen 80 is default
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    #listen 80 is default
    server_name example.com;
    ## here goes the rest of your conf...
}

This configuration will redirect all no-www requests to www requests.

You may also like...