nginx配置請求轉(zhuǎn)發(fā)不生效的實現(xiàn)
Bug Description
將vue打包部署時,修改了nginx.conf,在nginx.conf中配置了請求轉(zhuǎn)發(fā),但是請求轉(zhuǎn)發(fā)不生效,請求返回狀態(tài)碼404。
nginx配置如下:
location ~ ^/api(/|$) {
proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8081; #代理的ip
expires 24;
}
Reproduction Steps
1.編寫vue項目,使用npm run build打包,將打包后的文件夾dist放到nginx的html目錄下。
2.修改nginx.conf,配置請求轉(zhuǎn)發(fā)。
3.啟動nginx服務。
Reason
在本地開發(fā)環(huán)境,為了解決跨域問題,修改了vue.config.js:
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: { '^/api': '' },
ws: true,
secure: false
}
}
}
此處做了路由改寫,實際后端訪問地址為http://localhost:8081/,而nginx配置的代理地址為http://localhost:8081/api,導致請求定向錯誤。
Solution
將nginx.conf進行路由改寫:
location ~ ^/api(/|$) {
proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8081; #代理的ip
# 將 /api 替換為 /
rewrite ^/api(.*)$ $1 break;
expires 24;
}
正常轉(zhuǎn)發(fā),請求返回狀態(tài)碼200。
到此這篇關(guān)于nginx配置請求轉(zhuǎn)發(fā)不生效的實現(xiàn)的文章就介紹到這了,更多相關(guān)nginx 請求轉(zhuǎn)發(fā)不生效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mac安裝nginx且配置vue/springboot項目過程(本地/服務器)
文章涵蓋Mac和Linux安裝Nginx的步驟,包括配置路徑、自啟動、端口修改、前端部署及權(quán)限設(shè)置,解決常見問題以確保服務正常運行2025-07-07
nginx通過location配置代理的原理和實現(xiàn)方式
這篇文章主要介紹了nginx通過location配置代理的原理和實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03
分享nginx+php-fpm實現(xiàn)大文件下載排坑的過程
這篇文章主要介紹了nginx+php-fpm實現(xiàn)大文件下載排坑的過程,文中通過代碼實例相結(jié)合的形式給大家介紹的非常詳細,具有一定得參考借鑒價值,需要的朋友參考下吧2018-08-08

