nginx虛擬路徑中proxy_pass對後端請求的影響

假設nginx中的配置是這樣的:

server {

    listen 80;

    server_name x.x.x.x;

    . . . . . .

    location /subdir

    {

        proxy_pass http://y.y.y.y;

    }

}

那麼,當用戶請求http://x.x.x.x/subdir/other時,匹配到該區塊,nginx反向代理到後端時會保留虛擬路徑。nginx實際向後端發起的請求URL爲http://y.y.y.y/subdir/other。

 

假設nginx中的配置是這樣的:

server {

    listen 80;

    server_name x.x.x.x;

    . . . . . .

    location /subdir

    {

        proxy_pass http://y.y.y.y/;

    }

}

那麼,當用戶請求http://x.x.x.x/subdir/other時,匹配到該區塊,由於proxy_pass中有指定後端URI路徑,nginx代理請求到後端時不會保留虛擬路徑。nginx實際向後端發起的請求URL爲http://y.y.y.y//other。

 

假設nginx中的配置是這樣的:

server {

    listen 80;

    server_name x.x.x.x;

    . . . . . .

    location /subdir

    {

        proxy_pass http://y.y.y.y/upstream_subdir;

    }

}

那麼,當用戶請求http://x.x.x.x/subdir/other時,匹配到該區塊,由於proxy_pass中有指定後端URI路徑,nginx代理請求到後端時不會保留虛擬路徑。nginx實際向後端發起的請求URL爲http://y.y.y.y/upstream_subdir/other。

 

綜合上述三個示例可以發現,問題的關鍵就在於proxy_pass指令中是否有指定後端服務器的URI,這決定了nginx代理請求到後端時是否會保留location中的虛擬路徑。

 

當將後端服務器寫成upstream方式時,效果也是一樣的。比如:

upstream backend {

    server y.y.y.y:80;

}

server {

    listen 80;

    server_name x.x.x.x;

    . . . . . .

    location /subdir

    {

        proxy_pass http://backend/upstream_subdir;

    }

}

當用戶請求http://x.x.x.x/subdir/other時,nginx實際向後端發起的請求URL仍然爲http://y.y.y.y/upstream_subdir/other。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章