nginx:如何重写url以使用www和https

nginx:如何重写url以使用www和https,nginx,Nginx,如何重写url以始终使用www和https // 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

如何重写url以始终使用www和https

// 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
我已经使用以下方法向所有请求添加https,但是http呢?有没有一种有效的添加方法

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

谢谢

创建2个服务器块来处理异常,创建1个服务器块来处理常规内容

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

Tanhongta的回答很好,但您必须考虑nginx的默认服务器行为。如果没有匹配的服务器块,即使您定义了
server\u name
,它也将使用第一个

另外,不要忘记添加ssl证书和密钥,即使对于只有返回的块也是如此

我最后做了以下几件事:

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

这似乎合乎逻辑,但我有一些问题,所以我只尝试了一个服务器块,最后一个是443 ssl和www.domain.com。当我只有那个时,两个
https://www.domain.com
https://domain.com
工作。就像nginx忽略服务器名称一样?我没想到
https://domain.com
在这种情况下可以工作,对吗?