(1)配置 proxy_pass 时,当在后面的 url 加上了 /,相当于是绝对路径,则 Nginx 不会把 location 中匹配的路径部分加入代理 uri。
(2)如果配置 proxy_pass 时,后面没有 /,Nginx 则会把匹配的路径部分加入代理 uri。
server { listen 8081; server_name localhost; location / { root html; index index.html index.htm; } #情景1:proxy_pass后有/ ,表绝对路径,不把匹配部分加入最终代理路径(location 和proxy_pass结尾一致) #访问地址:http://localhost:8081/WCP.Service/wcp/modeladapter/download/asc.shtml #最终代理:http://10.194.171.7:13082/modeladapter/download/asc.shtml location /WCP.Service/wcp/modeladapter/download/ { proxy_pass http://10.194.171.7:13082/modeladapter/download/; } #访问地址:http://localhost:8081/model/asc.shtml #最终代理:http://127.0.0.1:8082/model/asc.shtml location /model/ { proxy_pass http://127.0.0.1:8082/model/; } #情景2:proxy_pass后有/ ,表绝对路径,不把匹配部分加入最终代理路径(location 和proxy_pass结尾不一致) #访问地址:http://localhost:8081/model/asc.shtml #最终代理:http://127.0.0.1:8082/asc.shtml location /model/ { proxy_pass http://127.0.0.1:8082/; } #情景3:proxy_pass后没有 / ,Nginx会把匹配部分带到代理的url #访问地址:http://localhost:8081/model/asc.shtml #最终代理:http://127.0.0.1:8082/model/asc.shtml location /model/ { proxy_pass http://127.0.0.1:8082; } #情景4 #访问地址:http://localhost:8081/model/asc.shtml #最终代理:http://127.0.0.1:8082/AAAmodel/asc.shtml location /model/ { proxy_pass http://127.0.0.1:8082/AAA; } #情景5 #访问地址:http://localhost:8081/model/asc.shtml #最终代理:http://127.0.0.1:8082/asc.shtml location /model { proxy_pass http://127.0.0.1:8082/; } #情景6 #访问地址:http://localhost:8081/modelBBB/asc.shtml #最终代理:http://127.0.0.1:8082/asc.shtml location /model { proxy_pass http://127.0.0.1:8082/; } location /opus-front-sso { proxy_pass http://10.194.170.94/opus-front-sso; } location /awater { proxy_pass http://10.194.170.94/awater; } }
... #全局块 events { #events块 ... } http #http块 { ... #http全局块 server #server块 { ... #server全局块 location [PATTERN] #location块 { ... } location [PATTERN] { ... } } server { ... } ... #http全局块 }
server { listen 8111; server_name localhost; location / { root /root/jarServer; try_files $uri $uri/ /index.html; index index.html; autoindex on; # 开启目录文件列表 autoindex_exact_size on; # 显示出文件的确切大小,单位是bytes autoindex_localtime on; # 显示的文件时间为文件的服务器时间 charset utf-8,gbk; # 避免中文乱码 }
nginx 设置 proxy_pass nginx本身就监听端口
如果您想在 Nginx 中设置 proxy_pass,但目标地址又是 Nginx 本身正在监听的端口,需要注意避免出现循环代理(proxy loop)的情况。以下是一种解决方法:
server { listen 80; server_name example.com; location / { proxy_pass http://localhost:8080; } }
上述配置中,Nginx 监听在端口 80,并将请求代理到本地的端口 8080。
nginx Copy server { listen 80; server_name example.com; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true; proxy_pass http://localhost:8080; proxy_redirect off; } }
上述配置中,我们添加了 proxy_set_header 指令,将一些常用的请求头传递给代理服务器。这样,后续在代理请求时,您可以检查 X-Nginx-Proxy 头的值,以确定是否已经被代理过。
在代理服务器(本地的端口 8080)上,您可以根据需要检查 X-Nginx-Proxy 头,如果已经被代理过,则可以选择不进行进一步的代理。
通过这种方式,您可以避免 Nginx 自身监听的端口发起循环代理的情况。
请注意,这只是一种示例解决方案,具体的配置取决于您的实际需求和环境。确保根据您的情况进行适当的配置和安全性考虑。