Properly setup redirects from www to non-www on nginx

In many online tutorials you will find just few lines like 

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

but actually you need much more, you need to include SSL certificates, otherwise you will get message about insecure site so you should have this

server {
    listen 443 ssl;
    ssl_certificate /path/to/server.cert;
    ssl_certificate_key /path/to/server.key;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

or actually this would be the best way to solve this all together

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

server {
    listen 443 ssl;
    ssl_certificate /path/to/server.cert;
    ssl_certificate_key /path/to/server.key;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /path/to/server.cert;
    ssl_certificate_key /path/to/server.key;
    server_name example.com;

    <locations for processing requests>
}

which can be found here on this link

https://serverfault.com/questions/258378/remove-www-and-redirect-to-htt…