'How does proxy_redirect correctly replace the Location URL?
I am using the following Nginx reverse proxy configuration.
server {
listen 80;
listen [::]:80;
server_name www.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $Host;
proxy_set_header x-forwarded-for $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
add_header Cache-Control no-store;
add_header Pragma no-cache;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
The vast majority of the time, it works well. However, problems occur when visiting URLs that have 301 redirects set.
For example, when visiting http://www.example.com/aaa/, it should redirect to http://www.example.com/bbb/
but it redirects incorrectly to http://127.0.0.1:3000/bbb/
After investigating this issue, I found that I should use the proxy_redirect parameter instead.
I found a description of proxy_redirect on the Nginx website, but I'm sorry that I didn't fully understand it.
As I understand it, the following usage can be used to solve my problem. The reason for not using a regular expression to get the rest of the URL is that it is automatically appended to the replacement string (am I right?) .
proxy_redirect http://$proxy_host/ /;
I also have two questions.
1、For non-80 ports, the $proxy_host variable should also output the port, something like 127.0.0.1:3000. But why does the official Nginx example use http://$proxy_host:8000/, is this a bug? Or is there something I'm not understanding?
2、Suppose that accessing http://www.example.com is incorrectly redirected to http://127.0.0.1:3000. In this case, does the above substitution syntax not work, because its substitution condition is at least http://127.0.0.1:3000/ (the / character is missing). How should I solve this problem? Should I use a regular expression to get the full URL for replacement? If so, is the following syntax correct?
proxy_redirect ~*http://127.0.0.1:3000(.*)$ http://www.example.com$1;
Thank you for your patience in reading, and thanks in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
