1、環境:
前端Nginx服務器:主機名:node5.a.com
IP:192.168.10.205 編譯安裝nginx 1.6.3
後端tomcat:
Server1--ip:192.168.10.209 主機名:node9.a.com
Server2--ip:192.168.10.210 主機名: node10.a.com
2、Ngginx配置:
user nginx;
worker_processes 1;
events {
use epoll;
worker_connections 4096;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
server_tokens off;
keepalive_timeout 65;
server_names_hash_max_size 1024;
gzip on;
gzip_proxied any;
gzip_min_length 1000;
gzip_comp_level 4;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_static on;
upstream tomcat { #定義一個tomcat服務器集羣,一下是包含的服務器的IP和端口;
server 192.168.10.209:8080;
server 192.168.10.210:8080;
}
server {
listen 80; #定義一個監聽的端口
server_name node5.a.com; #定義虛擬主機的名稱
location / {
root html/www; #虛擬主機的默認根目錄
index index.jsp index.html index.htm; #識別的首頁文件類型
}
location ~* \.(jsp|do)$ { #不區分帶小寫正則匹配,反請求.jsp和dp結尾的請求都會平均分配到後端服務器集羣tomcat。
proxy_pass http://tomcat; #將匹配請求轉發至tomcat集羣
}
location ~* \.(jpg|png|gif|jgeg|pdf)$ { #不區分大小寫匹配括號內定義的文件類型
proxy_pass http://192.168.10.209:8080; #轉發至該服務器
}
}
include html/*.conf; #讀取該目錄裏面的.conf文件
}
3,驗證:
1)訪問node5.a.com:
2)訪問node5.a.com/index.jsp
刷新一下:
注:由於在nginx配置文件中明確定義凡精確匹配.jsp結尾的請求會被轉發至tomcat集羣,因此該請求不會在nginx本機完成,而是會向服務器集羣轉發。另外由於在集羣中定義了兩臺服務器,所以會輪流分配用戶請求,即實現負載均衡的功能:
3)訪問node5.a.com/1.jpg
注:在Nginx.cong中定義~* \.(jpg|png|gif|jgeg|pdf)$ 即凡是以jpg|png|gif|jgeg|pdf結尾的請求都轉發至192.168.10.209服務器處理,因此需要把1.jpg文件放在192.168.10.209下的/opt/ROOT/1.jpg。