2013-08-30 25 views
15

我有HTTP重定向到SSL //同一主機像以下:使用nginx的

server { 

    listen 80; 
    listen 443 ssl; 

    ... 
    ... 
} 

我需要做的是重定向誰訪問我的店給用戶的https:/ /。問題是我有很多的語言:

https://mydomain.com/EN /店 https://mydomain.com/FR /店 等等

我嘗試這樣做,也沒有工作(nginx: configuration file /etc/nginx/nginx.conf test failed)

if ($server_port = 80) { 
    location (en|fr)/shop { 
     rewrite^https://$host$request_uri permanent; 
    } 
} 

回答

6

爲了使用正則表達式匹配location s,您需要在表達式前加上~~*

if ($server_port = 80) { 
    location ~ (en|fr)/shop { 
     rewrite^https://$host$request_uri permanent; 
    } 
} 

documentation

使用正則表達式,你必須使用一個前綴:

  1. "~"爲區分大小寫匹配
  2. "~*"不區分大小寫匹配

由於nginx的簡化版,允許嵌套的if塊內location塊,請嘗試以下配置:

if ($server_port = 80) { 
    rewrite ^/(en|fr)/shop https://$host$request_uri permanent; 
} 
+0

我買了你的代碼另一個錯誤:重新啓動nginx的:nginx的:EMERG]「位置」指令,在這裏不允許使用在 –

+2

@AdamSilver:你不能有'location'的'if'塊內(見位置的文檔)。如果路徑以「(en | fr)/ shop」開頭,只需將您的重寫規則更改爲僅重寫。 –

+0

但我會得到一個重定向循環! –

44

這也將是更大的NGINX最佳實踐做301重定向,而不是使用if語句(請參閱http://wiki.nginx.org/Pitfalls上的服務器名稱)。我創建了一個要點與配置了SSL,Rails和獨角獸

https://gist.github.com/Austio/6399964

這裏將是你的相關部分的nginx.conf。

server { 
    listen  80; 
    server_name domain.com; 
    return 301 https://$host$request_uri; 
} 
+0

(對不起,挖一箇舊線程)爲了避免不好的做法,我認爲這應該被標記爲答案。 –

+7

而不是硬代碼域名,我們可以這樣做:return 301 https:// $ host $ request_uri; –

+0

@NamNguyen更新了您的建議,謝謝! – Austio

2

理想的情況下,避免if語句,同時保留尾部的路徑:

server { 
    listen 80; 
    server_name example.com; 
    rewrite (.*) https://example.com$1 permanent; 
} 

永久花費的301

10

護理或者更好的是,避免了硬編碼服務器名稱

server { 
    listen 80; 
    rewrite (.*) https://$http_host$1 permanent; 
} 
2

另一種方式error_page 497

server { 
    listen 80; 
    listen 443; 

    ssl on; 
    error_page 497 https://$host$request_uri; 
    ssl_certificate  /etc/ssl/certs/ssl-cert-snakeoil.pem; 
    ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key; 
...