NGINX as proxy - redirect to www

Solution 1:

Your changing the wrong server block. The second server block contains:

server_name example.com www.example.com;

and needs to be split into two separate server blocks. You can then redirect from one to the other.

For example:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate ...;
    ssl_certificate_key ...;
    return 301 https://www.$server_name$request_uri;
}
server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate ...;
    ssl_certificate_key ...;
    ...
    ...
}