nginx反向代理,配置文件路径转发,重定向地址问题?
server {
listen 80; #设置监听IPV4的地址与端口
server_name 666666.dsto.com;
location / {
root /usr/share/nginx/html; #设置WEB应用根目录
index index.html index.htm; #设置默认首页文件
}
location /are/ {
#proxy_set_header Host $host; #是否转发host,后端通过host域名,分析你访问具体那个域名
proxy_set_header X-Real-IP $remote_addr; #获取前一节点的IP,并不一定是用户的真实IP。
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #获取多层级的proxy,链路反追踪,HTTP的请求端真实的IP
proxy_set_header X-NginX-Proxy true;
proxy_pass http://192.168.2.60:5005/;
}
location /baidu/ {
#proxy_set_header Host $host;
proxy_set_header X-Real-IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass https://www.baidu.com/;
}
error_page 404 403 500 502 503 504 /404.html; #错误,访问404.html
location = /404.html {
root /usr/share/nginx/html; #定义404.html所在路径
}
}
如上nginx配置sever模块,进行路径代理,
进行测试,现在访问:
访问1:666666.dsto.com/are/ 则访问到 http://192.168.2.60:5005/ 此时浏览器地址栏:https://666666.dsto.com/are/
访问2:666666.dsto.com/baidu/ 则访问到 https://www.baidu.com/ 此时浏览器地址栏:https://666666.dsto.com/baidu/
此时问题出现。http://192.168.2.60:5005/ 这个服务里面有2级页面和登录验证。
问题:
_当我要访问http://192.168.2.60:5005/help 二级页面时候。实际我需要访问的是666666.dsto.com/are/help/ (手动输入地址访问没问题)
实际情况是访问:https://666666.dsto.com/are/ 转发到 http://192.168.2.60:5005/ 的主页,然后点击服务的子页面/help,
此时浏览器路径会跳转为https://666666.dsto.com/help/ 报错404,即 /are/ 路径没有被重定向写入访问地址。丢失了/are/导致转发失败。
我要实现的服务里点击help子页面,重定向地址为:https://666666.dsto.com/are/help/
即访问这个服务时候,所有服务内的子页面跳转 实现地址自动重定向加入/are/
_
查询过资料,配置文件重写host、端口、路径等资料,包括访问头。测试后未完美解决。
个人水平一般,非从业者,希望专业人士,给与解答,谢谢。配置文件该怎么写。申请帮助。
location /are/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://192.168.2.60:5005/;
# 添加以下代码,实现地址自动重定向加入 /are/ 路径
proxy_redirect http://192.168.2.60:5005/ https://$host/are/;
}
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
根据您的描述,问题是由于在主页内无法正确设置链接,导致子页面无法正确访问。下面是一些可能的解决方案:
要让子页面以 /are/ 为前缀,您需要在服务中指定根路径。这通常可以在服务的配置文件中完成。例如,如果您使用的是 Flask 开发 Web 应用程序,并使用 Flask 的蓝图功能对应子页面,则可以将以下行添加到应用程序的初始化代码中:
app = Flask(__name__, static_url_path='/are/static')
这说明您想要访问您的资源,例如 CSS 文件,通过 URL /are/static 来访问。
如果您使用的是其他 Web 框架,请查看框架文档以查找类似的选项,并指定根 URL 路径为 /are/。
在您的 nginx 配置文件中,您可以使用 sub_filter 来更改响应的文本。例如,以下配置将把响应中的 /help 前缀替换为 /are/help/:
location /are/ {
...
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
sub_filter_once off;
sub_filter_types *;
sub_filter /help /are/help/;
...
}
说明:
sub_filter_once off
表示重复进行替换。sub_filter_types *
表示要对所有 MIME 类型执行替换,而不仅仅是 HTML。如果子页面中的链接采用相对路径,则无需修改 nginx 配置或 Web 服务器代码即可正确访问它们。例如,如果您的子页面位于 /help 页面下,则您可以将以下链接:
```
https://ask.csdn.net/help/foo