[Nginx] How to redirect http to https and www to non-www (and vice versa)

Today let's see some common redirections with Nginx

[Nginx] How to redirect http to https and www to non-www (and vice versa)

Hi, today let's see some common redirections with Nginx.

http redirection

(Photo credit: bloggingkeys.com)

http to https

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

www to non-www

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

And include https  

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

non-www to www

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

And include https  

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