2014-10-27 81 views
0

如何重寫url以使用www和https所有的時間?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 

我已經使用以下方式將https添加到所有請求中,但http又怎麼樣?有沒有一種有效的方式來添加它?

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

由於

回答

0

TanHongTat的答案是好的,但你必須考慮nginx的默認服務器行爲。如果沒有服務器塊匹配,即使您定義了server_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.. 
    # 
} 
2

創建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.. 
    # 
} 
+0

這似乎是合乎邏輯的,但我有一些問題,所以我只用一個服務器塊,最後一個443 SSL和www.domain.com嘗試。 當我只有這樣的時候,「https:// www.domain.com」和「https:// domain.com」都可以工作。這就像nginx忽略server_name?我沒有想到'https:// domain.com'在這種情況下工作,對嗎? – Michael 2014-10-29 13:59:16