nginx反向代理配置

最近在项目中使用nginx反向代理,根据不同的请求路径,将请求分发到不同服务。下面的示例主要完成如下功能

  • /prod/路径的请求分发到prod服务
  • /test/路径的请求分发到test服务

创建文件夹:/root/web/prod,/root/web/test;分别上传一个index.html文件,文件内容分别为:prod, test。

配置反向代理

修改/usr/local/nginx/conf/nginx.conf文件,在http节点下新增如下两个节点:

 1     //模拟prod服务
 2    server {
 3         listen 8081;
 4         server_name localhost;
 5 
 6         location / {
 7                 root /root/web/prod;
 8         }
 9     }
10 
11     //模拟test服务
12       server {
13         listen 8082;
14         server_name localhost;
15 
16         location / {
17                 root /root/web/test;
18         }
19     }

nginx反向代理主要使用指令“proxy_pass”,反向代理服务节点配置如下,

 1 server {
 2         listen       80;
 3         server_name  localhost;
 4 
 5         location / {
 6             root   html;
 7             index  index.html index.htm;
 8         }
 9 
10         location /prod/ {
11                  proxy_pass http://localhost:8081/;
12         }
13 
14         location /test/ {
15                 proxy_pass http://localhost:8082/;
16         }
17     }

保存修改后的配置文件,重新加载nginx.conf文件

1 /usr/local/nginx/sbin/nginx -s reload;

在浏览器中访问:http://ip/prod, htpp://ip/test, 分别显示prod, test字符串。

proxy_pass根据path路径转发时的"/"问题记录

在nginx中配置proxy_pass时,如果是按照^~匹配路径时,要注意proxy_pass后的url最后的/。当加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分也给代理走

1    location /prod/ {
2         proxy_pass http://localhost:8081/;
3     }

如上面的配置,如果请求的url是http://ip/prod/1.jpg会被代理成http://localhost:8081/1.jpg

    location /prod/ {
        proxy_pass http://localhost:8081;
    }

如上面的配置,如果请求的url是http://ip/prod/1.jpg会被代理成http://localhost:8081/prod/1.jpg

在使用proxy_pass进行反向代理配置时,一定要多注意是否需要加"/",该问题已经犯了很多次了,切忌,特别感谢如下参考的文章:proxy_pass根据path路径转发时的"/"问题记录

参考文章

proxy_pass根据path路径转发时的"/"问题记录

原文地址:https://www.cnblogs.com/pxset/p/10782971.html