Nginx: how to rewrite the url to use www and https

advertisements

How to rewrite the url to use www and https all the time?

// The url can have https but not www
https://example.com
// The url can have www but not https
http://www.example.com
// The url can have neither https, neither www
http://example.com 

=> rewrite to https://www.example.com

I already use the following to add https to all requests but what about http? Is there an efficient way of adding it?

server {
    listen    80;
    listen    [::]:80;
    return    301 https://$host$request_uri;
}

Thanks


Create 2 server blocks to handle the exceptions and 1 server block for the usual stuff.

server {
    listen         80;
    server_name    www.domain.com
                   domain.com;
    return         301 https://www.domain.com$request_uri;
}
server {
    listen         443 ssl;
    server_name    domain.com;
    return         301 https://www.domain.com$request_uri;
}
server {
    listen         443 ssl;
    server_name    www.domain.com;

    #
    # The usual stuff..
    #
}