2017-02-19 25 views
0

我需要重寫遠程URL到本地端口(有應用程序聽它)。防止ngnix嘗試解決刪除網址到本地

我的配置:

server { 
     listen  80; 
     server_name mysite.org; 

     location /foo { 
      proxy_pass http://127.0.0.1:8080; 
     } 
    } 

現在,當我訪問/foo的nginx試圖找到我的本地應用程序/foo路徑。像:http://127.0.0.1:8080/foo。但我需要強迫他們不要試圖獲得這條道路,而只需重寫爲http://127.0.0.1:8080

我該怎麼辦呢?

P.S.我試圖在http://127.0.0.1:8080/;處添加尾部斜槓,但沒有幫助。

回答

0

通過添加尾隨/proxy_pass,您正在創建從/foo/的映射,這對其他URI不起作用。例如/foo/bar將映射到//bar。您可以通過使用location /foo/ { ... }來解決問題,但是然後URI /foo不起作用,並且需要單獨修復。

作爲使用proxy_pass執行混疊功能的替代方法,您可以改爲使用rewrite ... break。有關更多信息,請參閱this document

嘗試:

location /foo { 
    rewrite ^/foo(?:/(.*))?$ /$1 break; 
    proxy_pass http://127.0.0.1:8080; 
} 

正則表達式/foo/後捕獲任何東西,但也允許/foo映射到/。它被分解爲:

1^ anchor beginning of line 
2 /foo part of URI we need to remove 
3 (?: begin non-capturing group 
4/ part of URI which is optional 
5 (.*) capture anything that must be used to create mapped URI 
6 )? close non-capturing group and make it optional 
7 $  anchor end of line 

我們希望$1表示一切都在第5步,因此拍攝使用非捕獲組。我們可以使用正常捕獲並重新編號爲$1$2

看到這個useful resource on regular expressions

+0

你能解釋一下'rewrite ^/foo(?:/(。*))?$/$ 1 break;'do? –