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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM