在Nginx location通用匹配规则中配置proxy_pass转发时,假设有如下location配置:
location /test {
proxy_pass http://localhost:8080/test;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-Proto "https";
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Real-IP $remote_addr;
}
如果我请求 http://localhost/test/a.jsp,则会将url根据匹配规则“/test”截取,然后将“/test”后面的内容(此处为“/a.jsp”)拼接到proxy_pass的后面,然后转发,也就是最后实际请求地址为:proxy_pass http://localhost:8080/test/a.jsp。
所以,如果location的匹配规则最后不加斜线'/',则proxy_pass的最后也不要加斜线,或者都加上斜线,不然就不能正确访问实际地址,导致404 not found错误。
注:正则匹配不适用,关于location的匹配规则,可以参考其他资料。
附:
作者在实际的项目布署中,遇到过404的问题,这个转发是去到spring cloud gateway的,配置如下:
location /api-cc {
proxy_pass http://190.31.0.191:8001/ ;
}
这样产生了404问题,但是改成
location /api-cc/ {
proxy_pass http://190.31.0.191:8001/ ;
}
如此加一个/就成功了,上面那一段配置对于一般的转发也是可以的,但是对于转发到spring cloud gateway就不行了,所以作者猜想是不是spring cloud gateway不允许在路径中出现两个斜线,比如:
http://190.31.0.191:8001//cc/api01
经过实际请求发现,果然猜想没错,如此问题就得到完美解答了。