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服務(wù)。
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)文章
Windows Server 2016 MySQL數(shù)據(jù)庫安裝配置詳細安裝教程
這篇文章主要介紹了Windows Server 2016 MySQL數(shù)據(jù)庫安裝配置詳細安裝教程,需要的朋友可以參考下2017-08-08
使用Nginx實現(xiàn)301跳轉(zhuǎn)至https的根域名示例代碼
這篇文章主要介紹了使用Nginx實現(xiàn)301跳轉(zhuǎn)至https的根域名,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04
centos環(huán)境下nginx高可用集群的搭建指南
為了防止Nginx單點故障造成服務(wù)器癱瘓,本文介紹了Nginx實現(xiàn)高可用集群構(gòu)建,下面這篇文章主要給大家介紹了關(guān)于centos環(huán)境下nginx高可用集群的搭建指南,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07
Nginx應(yīng)用之Location路由反向代理及重寫策略示例
本篇文章主要介紹了Nginx應(yīng)用之Location路由反向代理及重寫策略示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02

