How to redirect non-www to www and www to no-www in Nginx?

How can I redirect the www version of a website to the non-www version in Nginx when I have a combined server_name directive in my configuration file? In other words, I have the following line in my Nginx config file: server_name example.com www.example.com; and I would like to redirect all requests to www.example.com to example.com.

Here is the solution I came up with.

Redirect non-www to www

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

In this code, any request made to example.com will be redirected to www.example.com.

Solution for multiple domains

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

Redirect www to non-www

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

In this code, any request made to www.example.com will be redirected to example.com.

Solution for multiple domains

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

Solution for combined server_name directive.

To redirect the www version of a website to the non-www version or non-www to www in Nginx when you have a combined server_name directive in your configuration file, you can use the following code

server {
    server_name example.com www.example.com;
    if ($host = 'example.com') {
        return 301 $scheme://www.example.com$request_uri;
    }
}

# redirect to non-www version

server {
    server_name example.com www.example.com;
    if ($host = 'www.example.com') {
        return 301 $scheme://example.com$request_uri;
    }
}