見配置,摘自nginx.conf 里的server 段:
server { listen 80; server_name abc.163.com ; location / { proxy_pass http://ent.163.com/ ; } location /star/ { proxy_pass http://ent.163.com ; } }
里面有兩個location,我先說第一個,/ 。其實這里有兩種寫法,分別是:
location / { proxy_pass http://ent.163.com/ ; }
location / { proxy_pass http://ent.163.com ; }
出來的效果都一樣的。
第二個location,/star/。同樣兩種寫法都有,都出來的結果,就不一樣了。
location /star/ { proxy_pass http://ent.163.com ; }
當訪問 http://abc.163.com/star/ 的時候,nginx 會代理訪問到 http://ent.163.com/star/ ,并返回給我們。
location /star/ { proxy_pass http://ent.163.com/ ; }
當訪問 http://abc.163.com/star/ 的時候,nginx 會代理訪問到 http://ent.163.com/ ,并返回給我們。
這兩段配置,分別在于, proxy_pass http://ent.163.com/ ; 這個”/”,令到出來的結果完全不同。
前者,相當于告訴nginx,我這個location,是代理訪問到http://ent.163.com 這個server的,我的location是什么,nginx 就把location 加在proxy_pass 的 server 后面,這里是/star/,所以就相當于 http://ent.163.com/star/。如果是location /blog/ ,就是代理訪問到 http://ent.163.com/blog/。
后者,相當于告訴nginx,我這個location,是代理訪問到http://ent.163.com/的,http: //abc.163.com/star/ == http://ent.163.com/ ,可以這樣理解。改變location,并不能改變返回的內容,返回的內容始終是http://ent.163.com/ 。 如果是location /blog/ ,那就是 http://abc.163.com/blog/ == http://ent.163.com/ 。
這樣,也可以解釋了上面那個location / 的例子,/ 嘛,加在server 的后面,仍然是 / ,所以,兩種寫法出來的結果是一樣的。
PS: 如果是 location ~* ^/start/(.*)\.html 這種正則的location,是不能寫”/”上去的,nginx -t 也會報錯的了。因為,路徑都需要正則匹配了嘛,并不是一個相對固定的locatin了,必然要代理到一個server。