今天接到一個配置nginx的需求是:需要訪問某個域名時,nginx可以去掉前綴去代理訪問到后端
正常配置情況下:
在nginx配置文件中中設(shè)置了 location /prod-api/api
時 瀏覽器訪問 /prod-api/api
反向代理到后端服務(wù)后,后端服務(wù)接收到的url地址實(shí)際還是 /prod-api/api
需要實(shí)現(xiàn)的功能需求:
訪問url路徑/prod-api/api
經(jīng)過nginx反向代理后,到達(dá)后端服務(wù)的實(shí)際url地址為/api
。
以下是原nginx配置文件中l(wèi)ocation部分的配置內(nèi)容:
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root /usr/share/nginx/html/cashier;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /prod-api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:9076;
}
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
}
將上述代碼修改為如下nginx location代碼:
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root /usr/share/nginx/html/cashier;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location ^~/prod-api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:9076/;
}
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
}
注意點(diǎn):
- 在proxy_pass 反向代理地址最后加一個/
- 在location匹配的url路徑前添加^~/
location ^~/prod-api/:匹配任何以 /prod-api/ 開頭的地址,匹配符合以后,停止往下搜索正則,采用這一條
- 不可以使用:
proxy_set_header Host $http_host;
我在現(xiàn)有環(huán)境的nginx里添加這段配置之后,訪問會轉(zhuǎn)不過去,查看nginx日志也只能看到是404信息,并沒有更多定位問題的信息。檢查了許久也沒找到原因,于是注釋掉location
里面所有配置,里面只加proxy_pass
這段配置,結(jié)果nginx是能夠轉(zhuǎn)發(fā)成功的,這說明單獨(dú)來看這條location的配置是沒有問題的,很有可能是現(xiàn)有環(huán)境nginx里的某些配置影響到了這個轉(zhuǎn)發(fā)。
為了定位問題原因,location
下的配置逐個注釋來定位問題,最后發(fā)現(xiàn)當(dāng)注釋掉proxy_set_header Host $http_host ;
這條配置之后,就能成功轉(zhuǎn)發(fā)了。這才注意到是反向代理配置的問題。
此配置的作用是:把原h(huán)ttp請求的Header中的Host字段也放到轉(zhuǎn)發(fā)的請求里。
如果不加這一行的話,nginx轉(zhuǎn)發(fā)的請求header里就不會有Host字段,而服務(wù)器是靠這個Host值來區(qū)分你請求的是哪個域名的資源的。
但是現(xiàn)有環(huán)境中原有的配置也不能隨便刪掉,所以可以進(jìn)行如下設(shè)置:
即,在location里面添加一條 proxy_set_header Host $proxy_host;
配置。文章來源:http://www.zghlxwxcb.cn/news/detail-494965.html
設(shè)置 proxy_set_header Host $host 時,瀏覽器直接訪問 nginx,獲取到的 Host 是 $host 的值,沒有端口信息。此時代碼中如果有重定向路由,那么重定向時就會丟失端口信息,導(dǎo)致 404文章來源地址http://www.zghlxwxcb.cn/news/detail-494965.html
到了這里,關(guān)于nginx代理去掉URl前綴的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!