本文轉載自:https://pureage.info/2013/10/31/130.html
由於工作需要,開始分析nginx的proxy模塊,在分析之前,當然要先會用了。於是開始熟悉該模塊的一些指令,其中最基本的指令要屬proxy_pass了。nginx的英文文檔總是看着感覺有些別扭,於是按慣例先google了一些文章。
這一搜,就掉進坑里了。
這些文章里都把proxy_pass的目標地址是形如“127.0.0.1:8090”和“127.0.0.1:8090/”分開討論,認為后者“/“的作用是刪除url中匹配的部分,然后再討論目標地址中帶了uri的情況。
其實根本沒這么復雜,只有兩種情況:
(1)目標地址中不帶uri。即proxy_pass的參數形如”http://127.0.0.1:8090"。 此時新的目標url中,匹配的uri部分不做修改,原來是什么樣就是什么樣。
(2)目標地址中帶uri。即proxy_pass的參數形如“http://127.0.0.1:8090/dir1/dir2"
此時新的目標url中,匹配的uri部分將會被修改為該參數中的uri,如”http://127.0.0.1:8888/dir1/dir2."
有人說,你沒有討論ip和端口后帶不帶”/“的區別。其實是不需要的,因為”/“本身就是一種uri,很明顯屬於上面的第二種情況,只不過是把原來的uri修改為了現在的uri(”/”),看上去,像是刪除了原url中匹配的部分。如果不理解這一點,就會總想着去牢記、區分結尾帶不帶”/“的情況。
官方文檔也是這么敘述的,根本沒有提及半句“/“:
A request URI is passed to the server as follows:
If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:
location /name/ {
proxy_pass http://127.0.0.1/remote/;
}
If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:
location /some/path/ {
proxy_pass http://127.0.0.1;
}
測試部分如下。
如果配置為:
server {
listen 9090;
access_log /home/strider/project/nginx/nginx-1.4.2/log/access_9090.log;
location /test1/test2/{
proxy_pass http://127.0.0.1:8090;
}
}
則有如下對應關系:
127.0.0.1:9090/test1/test2/echo1----->127.0.0.1:8090/test1/test2/echo1
127.0.0.1:9090/test1/test2/---->127.0.0.1:8090/test1/test2
如果配置為:
server {
listen 9090;
access_log /home/strider/project/nginx/nginx-1.4.2/log/access_9090.log;
location /test1/test2/{
proxy_pass http://127.0.0.1:8090/;
}
}
則有如下對應關系:
127.0.0.1:9090/test1/test2/echo1----->127.0.0.1:8090/echo1
127.0.0.1:9090/test1/test2/---->127.0.0.1:8090/
如果配置為:
>server {
listen 9090;
access_log /home/strider/project/nginx/nginx-1.4.2/log/access_9090.log;
location /test1/test2/{
proxy_pass http://127.0.0.1:8090/test1;
}
}
則有如下對應關系:
127.0.0.1:9090/test1/test2/echo1----->127.0.0.1:8090/test1echo1
127.0.0.1:9090/test1/test2/---->127.0.0.1:8090/test1
如果配置為:
server {
listen 9090;
access_log /home/strider/project/nginx/nginx-1.4.2/log/access_9090.log;
location /test1/test2/{
proxy_pass http://127.0.0.1:8090/test3/test4/test5;
}
}
則有如下對應關系:
127.0.0.1:9090/test1/test2/echo1----->127.0.0.1:8090/test3/test4/test5echo1
127.0.0.1:9090/test1/test2/---->127.0.0.1:80990/test3/test4/test5