nginx是現在網站架構必不可少的工具,最常用的功能就是反向代理,資源動靜態分離,還有負載均衡。
1.反向代理
修改nginx.config 文件,通過將一個服務器主機地址綁定多個域名。運行多個服務。這時就需要nginx的反向代理。
server {
listen 80;
server_name nginx-01.XXX.cn; #nginx所在服務器的主機名
#反向代理的配置
location / { #攔截所有請求
root html;
proxy_pass [http://192.168.0.21:8080;](http://192.168.0.21:8080;) #這里是代理走向的目標服務器:tomcat
}
}
2.動靜分離
非接口類型的請求就交給nginx處理,減輕服務的壓力
#動態資源 index.jsp
location ~ .*\.(jsp|do|action)$ {
proxy_pass http://tomcat-01.XXX.cn:8080;
}
#靜態資源
location ~ .*\.(html|js|css|gif|jpg|jpeg|png)$ {
expires 3d;
}
3.負載均衡
在http這個節下面配置一個叫upstream的,后面的名字可以隨意取,但是要和location下的proxy_pass http://后的保持一致。
http {
# 是在http里面的, 已有http, 不是在server里,在server外面
upstream tomcats {
server shizhan02:8080 weight=1;#weight表示權重
server shizhan03:8080 weight=1;
server shizhan04:8080 weight=1;
}
#卸載server里
location ~ .*\.(jsp|do|action) {
proxy_pass [http://tomcats;](http://tomcats;) #tomcats是后面的tomcat服務器組的邏輯組號
}
}