Nginx - How do I force all server domains and server blocks to use non-www redirect?

There are many good results out there on how to redirect "www" to "non-www" and visa versa.

The most recommended solution is this:

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

This works well for a single website configuration file. However, it quickly duplicates configuration when you have multiple websites under one Nginx server.

I'd really like to avoid duplicating configuration on a service I'm working on...

So my assumed solution to catch all www.[anything.com] domains looks something like this:

server {
    listen 80;
    return 301 https://$host$request_uri;
}

However, I believe the $host variable still contains "www" inside (which makes sense).

I'm struggling to test this with my current configuration, so to save time, please could someone with more Nginx experience point me in the right direction beyond this point?

Thank you for your time! 😊


Solution 1:

You can use the following approach:

server {
    listen 80;
    server_name ~^(?:www\.)(.*)$;

    return 301 https://$1$request_uri;
}

The regular expression captures the part after www. to $1 variable, which is then used in the return statement.

https://nginx.org/r/server_name explains in more details how nginx decides which server block to use.