溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Nginx反向代理及緩存使用

發(fā)布時間:2020-08-01 07:56:02 來源:網(wǎng)絡(luò) 閱讀:697 作者:mb5d03569e7eb16 欄目:系統(tǒng)運維

博文結(jié)構(gòu)
反向代理
proxy緩存

nginx優(yōu)化

一.反向代理(案例)

1、反向代理(Reverse Proxy)方式是指以代理服務(wù)器來接受客戶端的連接請求,然后將請求轉(zhuǎn)發(fā)給網(wǎng)絡(luò)上的 web 服務(wù)器(可能是 apache、nginx、tomcat、iis 等),并將從 web 服務(wù)器上得到的結(jié)果返回給請求連接的客戶端,此時代理服務(wù)器對外就表現(xiàn)為一個服務(wù)器。

Nginx反向代理及緩存使用

如圖可以看出:反向代理服務(wù)器代理網(wǎng)站 Web 服務(wù)器接收 Http 請求,對請求進行轉(zhuǎn)發(fā)。而且nginx作為反向代理服務(wù)器可以根據(jù)用戶請求的內(nèi)容把請求轉(zhuǎn)發(fā)給后端不同的web服務(wù)器,例如靜動分離,再例如在 nginx 上創(chuàng)建多個虛擬主機,這樣就成功的做到了在瀏覽器中輸入不同域名(url)的時候訪問后端的不同 web 服務(wù)器或 web 群集。

2、反向代理的作用
①保護網(wǎng)站安全:任何來自 Internet 的請求都必須先經(jīng)過代理服務(wù)器

Nginx反向代理及緩存使用

②通過配置緩存功能加速 Web 請求:可以緩存真實 Web 服務(wù)器上的某些靜態(tài)資源,減輕真實 Web 服務(wù)器的負載壓力

Nginx反向代理及緩存使用

③實現(xiàn)負載均衡:充當(dāng)負載均衡服務(wù)器均衡地分發(fā)請求,平衡集群中各個服務(wù)器的負載壓力;

Nginx反向代理及緩存使用

  • 實驗環(huán)境

Nginx反向代理及緩存使用

下載nginx軟件包

192.168.222.128 nginx服務(wù)器
192.168.222.129 web
192.168.222.130 web

  • nginx服務(wù)器操作如下:
[root@localhost / ]#tar zxf ngx_cache_purge-2.3.tar.gz 
[root@localhost / ]#unzip nginx-sticky-module.zip
[root@localhost / ]#tar zxf nginx-1.14.0.tar.gz 
[root@localhost /]# yum -y install pcre-devel openssl-devel
[root@localhost /]#cd nginx-1.14.0/
[root@localhost nginx-1.14.0]#./configure --prefix=/usr/local/nginx   \
--user=nginx --group=nginx --with-http_stub_status_module --with-http_realip_module --with-http_ssl_module  \
--with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client  \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi  \
--with-pcre  --add-module=../ngx_cache_purge-2.3  \
--add-module=../nginx-sticky-module  \
--with-http_flv_module  \
[root@localhost nginx-1.14.0]# make && make install
[root@localhost nginx-1.14.0]# ln -s /usr/local/nginx/sbin/nginx  /usr/local/sbin/
[root@localhost nginx-1.14.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: [emerg] getpwnam("nginx") failed
\\可以看到報錯,沒有創(chuàng)建nginx用戶
[root@localhost nginx-1.14.0]# useradd -s /sbin/nologin -M nginx
[root@localhost nginx-1.14.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: [emerg] mkdir() "/var/tmp/nginx/client" failed (2: No such file or directory)
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
\\報錯顯示沒有創(chuàng)建目錄
[root@localhost nginx-1.14.0]# mkdir -p /var/tmp/nginx/client 
[root@localhost nginx-1.14.0]# 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@localhost nginx-1.14.0]# nginx
[root@localhost ~]# netstat -anpt | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:           LISTEN      9886/nginx: master  
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf 
\\在http中添加如下
 upstream backend {
        sticky;
        server 192.168.222.129:80 weight=1 max_fails=2 fail_timeout=10s;    
        server 192.168.222.130:80 weight=1 max_fails=2 fail_timeout=10s;
}
\\
weight : 輪詢權(quán)值也是可以用在 ip_hash 的,默認值為 1
max_fails :允許請求失敗的次數(shù),默認為 1。當(dāng)超過最大次數(shù)時,返回 proxy_next_upstream模塊定義的錯誤。
fail_timeout : 有兩層含義,一是在 10s 時間內(nèi)最多容許 2 次失??;二是在經(jīng)歷了 2 次失敗以后,10s 時間內(nèi)不分配請求到這臺服務(wù)器。

\\在location添加,可以把以前的localtion注釋掉
 location / {
        proxy_pass http://backend;
}
[root@localhost /]# nginx -s reload  //重載nginx服務(wù)
  • 模塊解釋
    nginx-sticky-module 模塊:這個模塊的作用是通過 cookie 黏貼的方式將來自同一個客戶端(瀏覽器)的請求發(fā)送到同一個后端服務(wù)器上處理,這樣一定程度上可以解決多個 backend servers 的 session 同步的問題 —— 因為不再需要同步,而 RR 輪詢模式必須要運維人員自己考慮 session 同步的實現(xiàn)。

load-balance 其它調(diào)度方案:

  • 輪詢(默認) : 每個請求按時間順序逐一分配到不同的后端服務(wù)器,如果后端某臺服務(wù)器,故障系統(tǒng)被自動剔除,使用戶訪問不受影響。Weight 指定輪詢權(quán)值,Weight 值越大,分配到的訪問機率越高,主要用于后端每個服務(wù)器性能不均的情況下。
    ip_hash : 每個請求按訪問 IP 的 hash 結(jié)果分配,這樣來自同一個 IP 的訪客固定訪問一個后端服務(wù)器,有效解決了動態(tài)網(wǎng)頁存在的 session 共享問題。當(dāng)然如果這個節(jié)點不可用了,會發(fā)到下個節(jié)點,而此時沒有 session 同步的話就注銷掉了。
    least_conn :請求被發(fā)送到當(dāng)前活躍連接最少的 realserver 上。會考慮 weight 的值。
    url_hash : 此方法按訪問 url 的 hash 結(jié)果來分配請求,使每個 url 定向到同一個后端服務(wù)
    器,可以進一步提高后端緩存服務(wù)器的效率。Nginx 本身是不支持 url_hash 的,如果需要使用這種調(diào)度算法,必須安裝 Nginx 的 hash 軟件包 nginx_upstream_hash 。
    fair :這是比上面兩個更加智能的負載均衡算法。此種算法可以依據(jù)頁面大小和加載時間長短智能地進行負載均衡,也就是根據(jù)后端服務(wù)器的響應(yīng)時間來分配請求,響應(yīng)時間短的優(yōu)先分配。Nginx 本身是不支持 fair 的,如果需要使用這種調(diào)度算法,必須下載 Nginx 的upstream_fair 模塊。

  • web
[root@localhost ~]# yum -y install httpd
[root@localhost ~]# echo aaaaaaaaaa > /var/www/html/index.html 
[root@localhost ~]# systemctl start httpd
  • 另一臺web
[root@localhost ~]# yum -y install httpd
[root@localhost ~]# echo bbbbbbbbbbb > /var/www/html/index.html 
[root@localhost ~]# systemctl start httpd
  • 測試效果如下
[root@localhost ~]# curl 127.0.0.1
aaaaaaaaaaaaaaa
[root@localhost ~]# curl 127.0.0.1
bbbbbbbbbbbb
[root@localhost ~]# curl 127.0.0.1
aaaaaaaaaaaaaaa
[root@localhost ~]# curl 127.0.0.1
bbbbbbbbbbbb
\\可以看到nginx服務(wù)器把請求分別給兩臺web
  • 可以編輯nginx啟動腳本
[root@localhost ~]# vim /etc/init.d/nginx 
#!/bin/bash
#chkconfig: 2345 99 20
#description: Nginx Service Control Script
PROG="/usr/local/nginx1.10/sbin/nginx"
PIDF="/usr/local/nginx1.10/logs/nginx.pid"
case "$1" in
        start)
           netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
           if [ $? -eq 0 ]
           then
              echo "Nginx service already running."
           else
              $PROG -t &> /dev/null
              if [ $? -eq 0 ] ; then
                $PROG
                echo "Nginx service start success."
              else
                $PROG -t
              fi
           fi
        ;;
        stop)
           netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
           if [ $? -eq 0 ]
           then
                kill -s QUIT $(cat $PIDF)
                echo "Nginx service stop success."
            else
                echo "Nginx service already stop"
            fi
        ;;
        restart)
                $0 stop
                $0 start
        ;;
        status)
           netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
           if [ $? -eq 0 ]
           then
                echo "Nginx service is running."
           else
                echo "Nginx is stop."
           fi
        ;;
        reload)
           netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
           if [ $? -eq 0 ]
           then
                $PROG -t &> /dev/null
              if [ $? -eq 0 ] ; then
                kill -s HUP $(cat $PIDF)
                echo "reload Nginx config success."
              else
                $PROG -t
              fi
           else
                echo "Nginx service is not run."
           fi   
        ;; 
        *)
                echo "Usage: $0 {start|stop|restart|reload}"
                exit 1
        esac
[root@localhost ~]#  chmod +x /etc/init.d/nginx 
[root@localhost ~]# chkconfig --add nginx
[root@localhost ~]# service nginx start
Nginx service start success.
[root@localhost ~]# service nginx status
Nginx service is running.

二.nginx緩存使用

緩存也就是將 js、css、image 等靜態(tài)文件從后端服務(wù)器緩存到 nginx 指定的緩存目錄下,既可以減輕后端服務(wù)器負擔(dān),也可以加快訪問速度,但這樣緩存及時清理成為了一個問題,所以需要 ngx_cache_purge 這個模塊來在過期時間未到之前,手動清理緩存。
nginx的web緩存功能只要就是由proxy_cache、fastcgi_cache指令集和相關(guān)指令集完成:

proxy_cache:負責(zé)反向代理緩存后端服務(wù)器的靜態(tài)內(nèi)容;
fastcgi_cache:主要用來處理fastcgi動態(tài)進程緩存;

  • 在nginx主配置文件中添加如下
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
…………    //省略部分內(nèi)容
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '"$upstream_cache_status"';            //記錄緩沖命中率,注意這是一個整段,所以只在末尾有一個分號
//以上內(nèi)容原本已經(jīng)存在,只需添加最后一行即可!
    access_log  logs/access.log  main;
     proxy_buffering on;        //代理時,開啟緩沖后端服務(wù)器的響應(yīng)
    proxy_temp_path /usr/local/nginx/proxy_temp;        //定義緩存臨時目錄
    proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=my-cache:100m inactive=600m max_size=2g;
//定義緩存目錄,具體信息已在配置文件外部進行說明
…………    //省略部分內(nèi)容
        location ~/purge(/.*) {                 //定義緩存清除策略
                allow 127.0.0.1;
                allow 192.168.222.0/24;
                deny all;
                proxy_cache_purge my-cache $host$1$is_args$args;
        }

        location / {
                proxy_pass http://lzj;            //請求轉(zhuǎn)向lzj定義的服務(wù)器列表
                proxy_redirect off;            指定是否修改被代理服務(wù)器返回的響應(yīng)頭中的 location 頭域跟 refresh 頭域數(shù)值
#例如:
 設(shè)置后端服務(wù)器“Location”響應(yīng)頭和“Refresh”響應(yīng)頭的替換文本。 假設(shè)后端服務(wù)器返回的
 響應(yīng)頭是 “Location: http://localhost:8000/two/some/uri/”,那么指令proxy_redirect  
# http://localhost:8000/two/ http://frontend/one/;將把字符串改寫為 “Location: 
# http://frontend/one/some/uri/”。                               
                proxy_set_header Host $host;    //允許重新定義或者添加發(fā)往后端服務(wù)器的請求頭
#Host 的含義是表明請求的主機名,nginx 反向代理服務(wù)器會向后端真實服務(wù)器發(fā)送請求,
#并且請求頭中的host字段重寫為proxy_pass指令設(shè)置的服務(wù)器。因為nginx作為反向代理使
#用,而如果后端真實的服務(wù)器設(shè)置有類似防盜鏈或者根據(jù) http 請求頭中的 host 字段來進行
#路由或判斷功能的話,如果反向代理層的nginx不重寫請求頭中的host字段,將會導(dǎo)致請求失敗。                                
                proxy_set_header X-Real-IP $remote_addr;
                                //web 服務(wù)器端獲得用戶的真實 ip 但是,實際上要獲得用戶的真實 ip,也可以通過下面的X-Forward-For

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                                #后端的 Web服務(wù)器可以通過 X-Forwarded-For 獲取用戶真實 IP,X_Forward_For 字段
#表示該條 http 請求是有誰發(fā)起的?如果反向代理服務(wù)器不重寫該請求頭的話,那么后端
#真實服務(wù)器在處理時會認為所有的請求都來自反向代理服務(wù)器,如果后端有防護策略
#的話,那么機器就被封掉了。因此,在配置用作反向代理的 nginx 中一般會增加兩條配置,以便修改 http 的請求頭部
                proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
                                #增加故障轉(zhuǎn)移,如果后端的服務(wù)器返回 502、504、執(zhí)行超時等錯誤,
#自動將請求轉(zhuǎn)發(fā)到upstream 負載均衡池中的另一臺服務(wù)器,實現(xiàn)故障轉(zhuǎn)移。
                proxy_cache my-cache;
                add_header Nginx-Cache $upstream_cache_status;
                proxy_cache_valid 200 304 301 302 8h;
                proxy_cache_valid 404 1m;
                proxy_cache_valid any 1d;
                proxy_cache_key $host$uri$is_args$args;
                expires 30d;
        }
[root@localhost ~]# 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@localhost ~]# nginx -s reload            //重新加載nginx配置文件
  • 訪問如下:

Nginx反向代理及緩存使用

刷新一下顯示如:

Nginx反向代理及緩存使用

  • 清除緩存

Nginx反向代理及緩存使用

  • 再重新訪問192.168.222.128時,如下:可以看到已經(jīng)清楚緩存了

Nginx反向代理及緩存使用

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI