三、nginx的反向代理(二)

反向代理实例二

实现效果:使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中nginx 监听端口为 9001,

访问 http://127.0.0.1:9001/dev/ 直接跳转到 127.0.0.1:8081
访问 http://127.0.0.1:9001/test/ 直接跳转到 127.0.0.1:8082

实验代码
第一步,准备两个 tomcat,一个 8001 端口,一个 8002 端口,并准备好测试的页面
第二步,修改 nginx 的配置文件
在 http 块中添加 server{}

先修改tomcat8081的server.xml文件

进入tomcat8081

cd /root/java/tomcat/tomcat8081/apache-tomcat-8.5.47/conf

vim server.xml

  

 启动tomcat8081

cd /root/java/tomcat/tomcat8081/apache-tomcat-8.5.47/bin

启动

  ./startup.sh

分别在tomcat8080和tomcat8081的/root/java/tomcat/tomcat8080/apache-tomcat-8.5.47/webapps和/root/java/tomcat/tomcat8081/apache-tomcat-8.5.47/webapps目录下创建两个文件,一个为dev文件,一个为test文件

在dev文件夹一个idnex.html,里面的内容为<h1>8080</h1>

在test文件夹一个idnex.html,里面的内容为<h1>8081</h1>

 访问http://119.23.47.237:8081/test/index.html和http://119.23.47.237:8080/dev/index.html

 

 要实现:

访问 http://119.23.47.237:9001/dev/ 直接跳转到 127.0.0.1:8081

访问 http://119.23.47.237:9001/test/ 直接跳转到 127.0.0.1:8082

 在 nginx.conf  配置文件中增加如下配置

cd /usr/local/nginx/conf

vim nginx.conf 修改

 server {
        listen       9001;
        server_name  119.23.47.237;

        location ~ /dev/ {
                proxy_pass http://119.23.47.237:8080;
        }
        location ~ /test/ {
                proxy_pass http://119.23.47.237:8081;
        }
    }

cd /usr/local/nginx/sbin目录重新启动nginx

./nginx -s reload

 访问http://119.23.47.237:9001/test/和http://119.23.47.237:9001/dev/

location 指令说明
  该指令用于匹配 URL。
  语法如下:
    1、= :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求。
    2、~:用于表示 uri 包含正则表达式,并且区分大小写。
    3、~*:用于表示 uri 包含正则表达式,并且不区分大小写。
    4、^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location
    块中的正则 uri 和请求字符串做匹配。注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。

原文地址:https://www.cnblogs.com/Amywangqing/p/14765738.html