2015-04-01 84 views
0

我一直在努力尋找解決方案,我有一個問題: 我需要重定向所有HTTP請求到https,除了特定位置下的特定頁面。 我有以下幾點:Nginx重定向到https問題

server { 
     listen  80; 
     listen  443 ssl; 
     server_name myserver; 
     root   /var/www/example.org/htdocs; 
     index  index.html; 
     . 
     . 
} 

我不能使用:

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

我發現here

一個很好的解決方案與解決方案的問題是,重定向進入不定式循環,解決方案是類似的,在我的變化之後:

map $uri $example_org_preferred_proto { 
    default "https"; 
    ~^/post/ "http"; 
} 
server { 
    listen 80; 
    listen 443 ssl; 
    server_name example.org; 
    root /var/www/example.org/htdocs; 

    if ($example_org_preferred_proto = "https") { 
     return 301 $example_org_preferred_proto://example.org$request_uri; 
    } 
} 

我理解這個問題的邏輯:

  1. 我得到這樣一個請求:http://wwww.example.com/test - >重定向到https://wwww.example.com/test

  2. 現在我得到這樣一個請求:https://wwww.example.com/test - >重定向到https://wwww.example.com/test

  3. 現在我收到如下請求:https://wwww.example.com/test - >重定向到https://wwww.example.com/test並進入循環....

我需要一種方法來重定向一次後停止。

+0

與論壇網站不同,我們不使用「謝謝」或「任何幫助表示讚賞」,或在[so]上簽名。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be - 刪除 - 從帖子)。順便說一句,它的「提前致謝」,而不是「感謝先進」 – 2015-05-01 04:37:48

回答

1
server { 
    listen  80; 
    server_name wwww.example.com; 
    root   /var/www/example.org/htdocs; 
    location /test { 
     try_files $uri $uri/ =404; 
    } 
    location/{ 
     return   301 https://$server_name$request_uri; 
    } 
} 

server { 
    listen  443 ssl; 
    ## here goes other ssl staff which you can find by link: 
    ## https://gist.github.com/paskal/628882bee1948ef126dd 
    server_name example.org; 
    root /var/www/example.org/htdocs; 
    location /test { 
     try_files $uri $uri/ =404; 
    } 
    location/{ 
     return   301 https://$server_name$request_uri; 
    } 
} 

最好的解決辦法是最簡單的一個。你只需要提供一個位置並重定向其他任何東西 - 這樣做。 如果您在使用兩個服務器模塊時遇到問題,請詳細描述它。

+0

感謝您的答案,但就像我提到我有:'服務器{聽80;聽443 ssl;'我可以我的服務器分裂了 – 2015-04-02 07:01:06

+0

@BobaFettlikesJS,爲什麼你不能? – 2015-04-02 08:06:37