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

Redirect non-www to www

For Single Domain:

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

For All Domains:

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

Redirect www to non-www

For Single Domain:

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

For All Domains:

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