2014-04-29 27 views
0

我想要http://example.com/test/4000(或其他一些號碼)到proxy_pass到http://localhost:4000/test如何在nginx中動態分配端口?

這是可能的,我該怎麼做?

+0

是的,這是可能的。但是你應該首先考慮一下url結構。你想要它'/ test/4000/path/to/file'還是'/ test/path/to/file/4000'。從我的角度來看,最好將端口設置爲路徑的第一部分('/ 4000/test/..'),或者更好地設置爲子域('http:// 4000.example.com/test') –

+0

感謝你的回覆。我同意我也希望港口先來。你可以發表一個如何做到這一點的例子嗎?我嘗試了幾種不同的方式,但沒有成功。 – user3409889

回答

0

這裏是例如:

server { 
    listen 80; 
    server_name example.com; 

    # default port for proxy 
    set $port 80; 

    # redirect /4000 --> /4000/ just to be sure 
    # that next rewrite works properly 
    rewrite ^(/\d+)$ $1/ redirect; 

    # rewrite /4000/path/to/file to /path/to/file 
    # and store port number to variable 
    rewrite ^/(?<port>\d+)(.+)$ $2; 

    location/{ 
     # proxy request to localhost:$port 
     proxy_pass http://localhost:$port; 
    } 
} 

它代理請求/PORT_NUMBER/path/to/filelocalhost:PORT_NUMBER/path/to/file。如果url不是以端口號開始,它會回落到80,所以對/path/to/file的請求將代理到localhost:80/path/to/file

沒有檢查端口號是否有效,因此不建議將其用於生產。無論如何,在生產中使用可變的端口號實在是個壞主意。