Michael
Michael

Reputation: 8748

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

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

Upvotes: 0

Views: 48

Answers (2)

Michael
Michael

Reputation: 8748

TanHongTat answers is good but you have to take into account the default server behavior of nginx. If no server block matches, it will take the first one even though you defined server_name.

Also, do not forget to add the ssl certificate and key even for the block with only a return.

I ended up doing the following:

# Default server for http
server {
    listen 80;
    listen [::]:80;
    return 301 https://www.domain.com$request_uri;
}

# Default server for https
server {
    listen 443;
    return 301 https://www.domain.com$request_uri;

    ssl on;
    ssl_certificate /..../ssl_certificate.crt;
    ssl_certificate_key /..../ssl_certificate.key;

    # Disable SSLv3 vulnerability
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
}

server {

    listen 443;
    server_name www.domain.com;

    ssl on;
    ssl_certificate /..../ssl_certificate.crt;
    ssl_certificate_key /..../ssl_certificate.key;

    # Disable SSLv3 vulnerability
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    #
    # The usual stuff..
    # 
}

Upvotes: 0

Tan Hong Tat
Tan Hong Tat

Reputation: 6864

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..
    # 
}

Upvotes: 2

Related Questions