nginx反向代理負載均衡簡述

基於瀏覽器實現分離案例
if ($http_user_agent ~ Firefox) {
rewrite ^(.)$ /firefox/$1 break;
}
if ($http_user_agent ~ MSIE) {
rewrite ^(.
)$ /msie/$1 break;
}
if ($http_user_agent ~ Chrome) {
rewrite ^(.*)$ /chrome/$1 break;
}

防盜鏈案例:
location ~* .(jpg|gif|jpeg|png)$ {
valid_referer none clocked www.idfsoft.com;
if ($invalid_referer) {
rewrite ^/ http://www.idfsoft.com/403.html;
}
}

nginx反向代理負載均衡簡述
nginx通常被用作後端服務器的反向代理,這樣就可以很方便的實現動靜分離以及負載均衡,從而大大提高服務器的處理能力。
nginx實現動靜分離,其實就是在反向代理的時候,如果是靜態資源,就直接從nginx發佈的路徑去讀取,而不需要從後臺服務器獲取了。
但是要注意,這種情況需要保證後端跟前端的程序保持一致,如果是靜態資源,就直接從nginx發佈的路徑去讀取,而不需要從後臺服務器獲取了。
nginx通過upstream模塊來實現簡單的負載均衡,upstream需要定義在http段內
在upstream段內,定義一個服務器列表,默認的方式是輪詢,若要確定同一個訪問者發出的請求總是由同一個後端服務器來處理,可以設置ip_hash,如:
upstream idfsoft.com {
ip_hash;
server 127.0.0.1:9080 weight=5;
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:1111;
}

實現簡單的負載均衡

試驗環境三臺主機:
192.168.56.11 安裝nginx,作反向代理
192.168.56.12 安裝nginx,作後端服務器
192.168.56.13 安裝htppd,作後端服務器
三臺機器安裝好服務後啓動,並關閉防火牆,selinux。

192.168.56.11服務器上操作:
修改nginx配置文件
在http段內server段上邊添加upstream模塊:
[root@heyuanjie ~]# vi /usr/local/nginx/conf/nginx.conf
upstream web {
server 192.168.56.12;
server 192.168.56.13;
}
定義好upstream後,需要在server段內添加如下內容:
location / {
proxy_pass http://web;
}

以上兩段內容中的web名可以自定義,但需要做到見名知意,並且兩者要對應一樣。
修改完配置文件檢查語法錯誤,並重啓服務
[root@heyuanjie ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@heyuanjie ~]# nginx -s reload

在192.168.56.12服務器上操作,創建網頁文件輸入內容,用於後續驗證
[root@hyj ~]# cd /usr/local/nginx/html/
[root@hyj html]# echo 'you are my rose'> index.html
在192.168.56.13服務器上操作 ,創建網頁文件輸入內容,用於後續驗證
[root@hejie ~]# echo 'ran,you are my love!' > /var/www/html/index.html

通過ip192.168.56.11訪問

nginx反向代理負載均衡簡述

再次輸入ip192.168.56.11訪問,實現輪詢

nginx反向代理負載均衡簡述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章