proxy_pass的小說明

proxy_pass的小說明

在 nginx 中配置 proxy_pass 時,遇到了一些小坑,特加以說明,防止之後忘記。html

proxy_pass http://backup/;

當加上了 / ,至關因而絕對根路徑,nginx 不會把location 中匹配的路徑部分代理走;nginx

location ^~ /static/ 
{ 
# http://backup/。。。 不帶location中的東西
# 只要proxy_pass後面有東西就不帶location中的東西
proxy_pass http://www.test.com/; 
}
# location中的匹配路徑爲/static/。加了/以後proxy_pass 不會加上/static/
# curl http://localhost:3000/static/index.html
# proxy_pass 轉發爲 http://www.test.com/index.html

proxy_pass http://backup;

若是沒有/,則會把匹配的路徑部分也給代理走。curl

location ^~ /static/ 
{ 
# 帶上location中的東西
proxy_pass http://www.test.com; 
}
# location中的匹配路徑爲/static/。不加 / 後proxy_pass會加上 /static/
# curl http://localhost:3000/static/index.html
# proxy_pass 轉發爲 http://www.test.com/static/index.html

用在 location 的正則匹配中的坑 。。。

location 中 ~ (區分大小寫)與 ~* (不區分大小寫)標識均爲正則匹配,若是的話想在這裏用的話,則 proxy_pass 中的 http://backup; 後面不能帶有url。google

以下寫法會報錯url

location ~* /static/(.*)
{ 
# 此處 location 爲正則匹配,proxy_pass 後面不能有 /test 
proxy_pass http://www.test.com/test; 
}

若是 http://backup; 不帶url 。這麼寫是沒有問題的代理

location ~* /static/(.*)
{ 
# 此處 location 爲正則匹配,proxy_pass 後面不能有 /test 
proxy_pass http://www.test.com; 
}

在proxy_pass 中使用變量

proxy_pass中能夠使用變量,可是若是變量涉及到域名的話 須要使用resolver指令解析變量中的域名(由於nginx一開始就會解析好域名)code

### 不涉及到域名變量
location ~* /aa/bb(.*) {
    # 正常使用變量,注意此處爲location的正則匹配 proxy_pass 不能帶 /
    # 轉發後爲 127.0.0.1:9999/test
    proxy_pass http://backup$1;
}

### 涉及到域名的變量
location /aa/bb {
    # google 域名解析
    resolver 8.8.8.8;
    # 此處變量涉及到了域名 須要調用resolver指令進行解析下不然會報錯。
    set $myhost "www.test.com"; 
    proxy_pass http://$myhost;
}

rewrite 重寫後的 url 會忽略proxy_pass後路徑

# curl 127.0.0.1:8888/aa/bb/ccc
location /aa/bb {
    rewrite /aa/bb(.*) /re$1 break;
    proxy_pass http://backup;
}
# 轉發後獲得 127.0.0.1:9999/re/ccc
location /aa/bb{
    rewrite /aa/bb(.*) /re$1 break;
    # rewrite 重寫後的 url 路徑會 忽略 /asd 至關於 http://backup;什麼都不帶
    proxy_pass http://backup/asd;
}
# 此處轉發後一樣獲得 127.0.0.1:9999/re/ccc
相關文章
相關標籤/搜索