Nginx反向代理重寫URL的實現(xiàn)方案
需求
nginx 服務器代理前端項目,并且反代后端服務器。開發(fā)時使用沒有什么問題,部署后存在同樣請求根地址的情況,輸入nginx的地址localhost:3000能夠訪問到前端地址,但是去調(diào)用后端接口就會出現(xiàn)報錯,看來我對nginx還掌握的不夠,發(fā)現(xiàn)是調(diào)用后端接口的時候每次請求中都會多/api/,但是后端接口路徑并沒有多這個/api/,最后通過重寫url解決問題。
一般反向代理
一般會定義一個統(tǒng)一前綴,比如:api,則配置如下
server {
listen 80;
server_name default;
location /api/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://example.com;
}
}則請求到 http:localhost/api/findOne時,會轉(zhuǎn)發(fā)到 http://example.com/api/findOne。
設(shè)置proxy_pass即可。請求只會替換域名,不會將/api/也替換掉。
我現(xiàn)在想要訪問http:localhost/api/findOne轉(zhuǎn)發(fā)到http://example.com/findOne,去掉/api/則可按照如下兩種配置。
解決方案
方案一 使用 rewrite,注意到 proxy_pass結(jié)尾沒有 /, rewrite 重寫了 url,則最終的請求為http://example.com/findOne
server {
listen 80;
server_name default;
location /api/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://example.com;
}
}方案二 在 proxy_pass 后增加 / 則 nginx 會將/api之后的內(nèi)容拼接到 proxy_pass 之后。
server {
listen 80;
server_name default;
location /api/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://example.com/;
}
}到此這篇關(guān)于Nginx反向代理重寫URL的實現(xiàn)方案的文章就介紹到這了,更多相關(guān)Nginx反向代理重寫URL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Nginx實現(xiàn)404錯誤自動跳轉(zhuǎn)到首頁的配置過程
當用戶在訪問網(wǎng)站的過程中遇到404錯誤時,通常情況下應該顯示一個友好的錯誤頁面,而不是僅僅顯示一個簡單的錯誤提示,在Nginx中,可以通過配置來實現(xiàn)404錯誤自動跳轉(zhuǎn)到首頁的功能,下面將詳細介紹如何進行配置,需要的朋友可以參考下2023-12-12
nginx 虛擬主機設(shè)置實例(多網(wǎng)站配置)
Nginx 虛擬主機設(shè)置一例,主要是針對虛擬主機的設(shè)置,多網(wǎng)站配置方法,需要的朋友可以參考下2013-02-02
Ubuntu服務器已下載Nginx安裝包的安裝步驟(最新推薦)
在Ubuntu服務器上安裝已下載的 Nginx,需完成依賴安裝、解壓編譯、配置安裝及服務驗證等步驟,本文給大家介紹Ubuntu服務器已下載Nginx安裝包的安裝步驟,感興趣的朋友跟隨小編一起看看吧2025-10-10

