見(jiàn)配置,摘自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 ; } }
里面有兩個(gè)location,我先說(shuō)第一個(gè),/ 。其實(shí)這里有兩種寫(xiě)法,分別是:
location / { proxy_pass http://ent.163.com/ ; }
location / { proxy_pass http://ent.163.com ; }
出來(lái)的效果都一樣的。
第二個(gè)location,/star/。同樣兩種寫(xiě)法都有,都出來(lái)的結(jié)果,就不一樣了。
location /star/ { proxy_pass http://ent.163.com ; }
當(dāng)訪(fǎng)問(wèn) http://abc.163.com/star/ 的時(shí)候,nginx 會(huì)代理訪(fǎng)問(wèn)到 http://ent.163.com/star/ ,并返回給我們。
location /star/ { proxy_pass http://ent.163.com/ ; }
當(dāng)訪(fǎng)問(wèn) http://abc.163.com/star/ 的時(shí)候,nginx 會(huì)代理訪(fǎng)問(wèn)到 http://ent.163.com/ ,并返回給我們。
這兩段配置,分別在于, proxy_pass http://ent.163.com/ ; 這個(gè)”/”,令到出來(lái)的結(jié)果完全不同。
前者,相當(dāng)于告訴nginx,我這個(gè)location,是代理訪(fǎng)問(wèn)到http://ent.163.com 這個(gè)server的,我的location是什么,nginx 就把location 加在proxy_pass 的 server 后面,這里是/star/,所以就相當(dāng)于 http://ent.163.com/star/。如果是location /blog/ ,就是代理訪(fǎng)問(wèn)到 http://ent.163.com/blog/。
后者,相當(dāng)于告訴nginx,我這個(gè)location,是代理訪(fǎng)問(wèn)到http://ent.163.com/的,http: //abc.163.com/star/ == http://ent.163.com/ ,可以這樣理解。改變location,并不能改變返回的內(nèi)容,返回的內(nèi)容始終是http://ent.163.com/ 。 如果是location /blog/ ,那就是 http://abc.163.com/blog/ == http://ent.163.com/ 。
這樣,也可以解釋了上面那個(gè)location / 的例子,/ 嘛,加在server 的后面,仍然是 / ,所以,兩種寫(xiě)法出來(lái)的結(jié)果是一樣的。
PS: 如果是 location ~* ^/start/(.*)\.html 這種正則的location,是不能寫(xiě)”/”上去的,nginx -t 也會(huì)報(bào)錯(cuò)的了。因?yàn)椋窂蕉夹枰齽t匹配了嘛,并不是一個(gè)相對(duì)固定的locatin了,必然要代理到一個(gè)server。