Nginx做反向代理的三种配置

Nginx做反向代理的三种配置。

 

目标: 通过访问 http://192.168.43.196:9001/sunny/   自动转发到  http://127.0.0.1:8081/sunny/    

实现图:

方法一:配置文件中直接添加server标签

  (1) 需要一台tomcat,我的tomcat 访问路径为:http://127.0.0.1:8081/sunny/    

(2)配置nginx.conf  在最后配置文件最后添加

server {
  listen 9001;            #  nginx监听的端口
  server_name 192.168.43.196;   #  nginx监听的IP地址

  location / {
  proxy_pass http://127.0.0.1:8081;  # tomcat的访问的路径 ('/sunny 是我项目路径,这里不能配置')
  }
}

# 启动Nginx ,Tomcat 。浏览器访问 http://192.168.43.196:9001/sunny/   就自动转发到  http://127.0.0.1:8081/sunny/    

 

方法二:

在nginx.conf中的http标签中添加upstream  ,在server中添加  location,修改监听端口和IP

http标签中:

upstream sunnypool{
  server 192.168.43.196:9001;
}

server标签中:

修改
 listen 9001;              #修改监听端口为9001,默认是80
 server_name 192.168.43.196;   #修改监听IP,默认是localhost

添加

location / {
  proxy_pass http://sunnypool;
  root html;
  index index.html index.htm;
}

# 启动Nginx ,Tomcat 。浏览器访问 http://192.168.43.196:9001/sunny/   就自动转发到  http://127.0.0.1:8081/sunny/   

 

方法三:增加配置文件

说明:方法三是方法二的变形,写起来更灵活

添加配置文件:sunny_pool,sunny_proxy

 

(1)sunny_pool中添加内容:

  upstream sunny_pool {
    server 127.0.0.1:8081;
  }

(2)sunny_proxy中添加内容:

  location /sunnypool/ {
    proxy_pass http://sunny_pool/sunnypool/;
  }

(3)nginx.config的http标签中添加

  include sunny_pool;

(4)nginx.config的server标签中添加

    include sunny_proxy;

(5)nginx.config的server标签修改  listen , server_name 为

  listen 9001;
  server_name 192.168.43.196;

 

 

 

# 启动Nginx ,Tomcat 。浏览器访问 http://192.168.43.196:9001/sunny/   就自动转发到  http://127.0.0.1:8081/sunny/   

 

另外两篇Nginx心得。

Nginx做动静分离:https://www.cnblogs.com/sunnycc/p/14213980.html

Nginx做负载均衡:https://www.cnblogs.com/sunnycc/p/14213670.html

posted @ 2020-12-29 23:59  爵士灬  阅读(2345)  评论(0编辑  收藏  举报