四、Nginx 配置实例 --- 反向代理

4.1、反向代理实例一

实现效果:使用 nginx 反向代理,访问虚拟机地址,直接跳转到本地的程序

实现过程:

  • 在本地启动一个 tomcat 服务,在本地可以访问到。

  • 在 nginx.conf 中增加配置

    server {
        listen       80;
        server_name  nginx所在的主机ip;
        
        location / {
            proxy_pass tomcat所在的主机ip以及端口号;
            index  index.html index.htm;
        }
    }
  • 启动 nginx 服务

  • 在本机访问 nginx 的地址,显示 tomcat 的页面

4.2、反向代理实例二

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

实现过程:

  • 准备两个 tomcat 服务,端口号分别为 8082,8081 设置 nginx 监听的端口号为 9001

  • 修改 nginx 的配置文件如下(添加一个server块):

    server {
        listen       9001;
        server_name  localhost;
    ​
        location ~ /user/ {
            proxy_pass http://192.168.1.148:8081;
            index  index.html index.htm;
        }
    ​
        location ~ /role/ {
            proxy_pass http://192.168.1.148:8082;
            index  index.html index.htm;
        }
    }
     

    注意:tomcat 的访问路径需要跟 nginx 配置路径一致,比如 nginx 配置的 /user/ 路径 tomcat 也要通过 /user路径访问

原文地址:https://www.cnblogs.com/cuilichao/p/13730726.html