1. 程式人生 > >nginx實現動態/靜態檔案快取-技術流ken

nginx實現動態/靜態檔案快取-技術流ken

1.簡介

本系列博文將分為三大部分,這是第一部分。分別介紹nginx的動態以及靜態檔案的快取,使用nginx實現反向代理,以及nginx實現負載均衡。相信在讀完本篇博文之後,你會對nginx強大的應用功能驚歎不已,並且深深的愛上這款輕量級web服務程式。

2.nginx實現靜態檔案快取實戰

1.nginx靜態檔案快取

如果要熟練使用nginx來實現檔案的快取,那下面的幾個指令你必須要牢記於心

指令1:proxy_cache_path

作用:設定快取資料的相關資訊

    Syntax:     proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
    Default:     —
    Context:     http

    值:
        path:快取目錄的位置
        levels:指定使用幾級快取目錄
        keys_zone:指定快取區域的名稱和快取空間的大小

    例子:
        proxy_cache_path 
/data/nginx/cache levels=1:4 keys_zone=mycache:10m; 說明 1:表示一級目錄可以由1個字元來構成 4:表示二級目錄可以由4個字元來構成 mycache:是這個快取區域的名稱 10m:可以快取10M大小的資料 快取結果 /data/nginx/cache/c/29ad/b7f54b2df7773722d382f4809d65029c 說明 /data/nginx/cache/:這裡是快取目錄 c:因為一級目錄可以由1個字元構成,所有這裡隨機出現一個c 29ad:二級目錄由4個隨機字元構成 b7f54b2df7773722d382f4809d65029c:快取的資料

指令2:proxy_cache

    作用:呼叫快取

    Syntax:     proxy_cache zone | off;
    Default:     proxy_cache off;
    Context:     http, server, location
    注意:      該指令寫在不同的位置,快取資料物件也不同

指令3:proxy_cache_min_uses

作用:指定一個檔案至少需要被使用者訪問多少次以後,才會被快取,預設1

    Syntax:     proxy_cache_min_uses number;
    Default:     proxy_cache_min_uses 
1; Context: http, server, location

指令4:proxy_cache_purge

Syntax:     proxy_cache_purge string ...;
    Default:     —
    Context:     http, server, location

    使用場景:上游伺服器中的資源發生了更改,但是快取中的資料尚未過去,這個時候就需要手動執行purge讓快取中的資料過去
    使用舉例:
        http {
            proxy_cache_path /data/nginx/cache levels=1:4 keys_zone=mycache:10m;

            server {
                listen 10.220.5.196:80;
                location / {
                    proxy_pass http://10.220.5.180:80:
                    proxy_cache mycache;
                    ....
                    ....
                }

                location = /cleanCache {
                    allow=
                    deny=
                    proxy_cache_purge mycache;  #這裡需要指定上面定義的快取名稱
                    ...
                    ...
                    ...
                }
            }
        }

指令5:proxy_cache_valid

    作用:定義快取資料的有效期

    Syntax:     proxy_cache_valid [code ...] time;
    Default:     —
    Context:     http, server, location

    例子:
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 301      1h;
        proxy_cache_valid any      1m;

指令6:proxy_cache_key

作用:指定快取的key的名稱

    Syntax:     proxy_cache_key string;
    Default:     proxy_cache_key $scheme$proxy_host$request_uri;
    Context:     http, server, location

    例子:
        proxy_cache_key "$host$request_uri $cookie_user";
        proxy_cache_key "$uri"

2.nginx實現快取配置

1.環境準備

centos7.5

NGINX伺服器端IP:172.20.10.8/28

HTTPD伺服器端IP:172.20.10.7/28

HTTPD伺服器端IP:172.20.10.9/28

客戶端IP:172.20.10.4/28

2.nginx伺服器端

使用yum下載nginx需要使用網路yum源,複製下面的程式碼到你的yum倉庫即可下載

[ken]
name=ken
enabled=1
gpgcheck=0
baseurl=https://mirrors.aliyun.com/epel/7Server/x86_64/

下載nginx

[[email protected] ~]# yum install nginx -y

配置nginx檔案

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    #include /etc/nginx/conf.d/*.conf;
proxy_cache_path /ken levels=1:2 keys_zone=kenken:100m;
add_header host $server_addr;
add_header cachestatus $upstream_cache_status;
    server {
        listen       80 default_server;
 listen       [::]:80 default_server;
        server_name  _;
        root         /var/www/html;

        # Load configuration files for the default server block.
        # include /etc/nginx/default.d/*.conf;

        location / {
        proxy_pass http://172.20.10.7:80;
        proxy_set_header host $host;
        proxy_set_header realip $remote_addr;

        proxy_cache kenken;
        proxy_cache_min_uses 3;
        proxy_cache_valid any 10m;
        }
    }
}

建立快取目錄

[[email protected] ~]# mkdir /ken

更改快取目錄的屬主和屬組

[[email protected] ~]# chown -R nginx.nginx /ken

啟動nignx

[[email protected] ~]# systemctl start nginx
[[email protected] ~]# ss -tnl | grep 80
LISTEN     0      128          *:80                       *:*                  
LISTEN     0      128         :::80                      :::*      

3.配置web服務端

下載httpd

[[email protected] ~]# yum install httpd -y

準備測試檔案

[[email protected] ~]# echo "this is 172.20.10.7 for test">>/var/www/html/index.html

啟動httpd

[[email protected] ~]# systemctl restart httpd

4.瀏覽器測試

輸入nginx伺服器端的IP地址

輸入172.20.10.8的地址成功訪問172.20.10.7的頁面

檢視web伺服器端的訪問日誌

[[email protected] ~]# tail -f /var/log/httpd/access_log

172.20.10.8 - - [02/Oct/2018:22:40:43 +0800] "GET / HTTP/1.0" 200 29 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36"

成功捕捉到來自172.20.10.8的訪問請求

我們去檢視nginx服務端是否已經有快取產生

[[email protected] /]# ls /ken/e/55/58be92261b4ffa2c4fe7e92be2f0255e 

測試成功!

在nginx伺服器端已經產生了快取,再次重新整理瀏覽器介面,在web伺服器端都不會再產生訪問日誌,因為現在客戶請求是直接從快取提取的,沒有再往後方節點來訪問檔案,這樣可以大大提高網站的負載和併發能力。

3.nginx實現動態檔案快取實戰

在完成了上面的靜態檔案快取之後,相信動態檔案的快取對你來說也是輕而易舉了,下面我們一鼓作氣完成對動態檔案的快取吧。

1.環境準備

centos7.5

NGINX伺服器端IP:172.20.10.8/28

WEB伺服器端IP:172.20.10.9/28

2.配置nginx伺服器端

下載php

[[email protected] ~]# yum install php php-fpm -y

配置nginx檔案

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    #include /etc/nginx/conf.d/*.conf;
fastcgi_cache_path /kenken levels=1:2 keys_zone=kenken:100m;
add_header host $server_addr;
add_header cachestatus $upstream_cache_status;
    server {
        listen       80 default_server;
 listen       [::]:80 default_server;
        server_name  _;
        root         /var/www/html;
        index index.php;
        # Load configuration files for the default server block.
        # include /etc/nginx/default.d/*.conf;

        location ~^/.*(\.php)$ {
        fastcgi_pass 172.20.10.9:9000;
        fastcgi_index index.php;
        include fastcgi.conf;

        fastcgi_cache kenken;
        fastcgi_cache_valid any 10m;
        fastcgi_cache_key $request_uri;
        }
}
}

建立快取目錄,並修改許可權

[[email protected] ~]# mkdir /kenken
[[email protected] ~]# chown -R nginx.nginx /kenken

nginx語法檢測

[[email protected] ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

啟動nginx

[[email protected] ~]# systemctl restart nginx

3.配置web伺服器端

下載所需服務程式

[[email protected] ~]# yum install httpd php-fpm php -y

配置php-fpm

[[email protected] ~]# vim /etc/php-fpm.d/www.conf
...
 10 ;   '/path/to/unix/socket' - to listen on a unix socket.
 11 ; Note: This value is mandatory.
 12 listen = 172.20.10.9:9000   #修改為本機ip地址
 13 
 14 ; Set listen(2) backlog. A value of '-1' means unlimited.
 15 ; Default Value: -1
 16 ;listen.backlog = -1
 17 
 18 ; List of ipv4 addresses of FastCGI clients which are allowed to connect.
 19 ; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
 20 ; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
 21 ; must be separated by a comma. If this value is left blank, connections will be
 22 ; accepted from any ip address.
 23 ; Default Value: any
 24 listen.allowed_clients = 172.20.10.8  #修改為nginx服務端地址
...

啟動php-fpm

[[email protected] ~]# systemctl restart php-fpm
[[email protected] ~]# ss -tnl
State       Recv-Q Send-Q               Local Address:Port                              Peer Address:Port              
LISTEN      0      128                    172.20.10.9:9000                                         *:*   

準備動態測試檔案

[[email protected] ~]# cd /var/www/html/
[[email protected] html]# ls
index.html
[[email protected] html]# vim test.php
<?php
phpinfo();
?>

瀏覽器輸入nginx服務端ip地址進行測試

訪問成功,重新整理幾次檢視nginx是否已經產生快取

[[email protected] ~]# ls /kenken/
1/ b/ e/ 
[[email protected] ~]# ls /kenken/b/fe/c86156f7dcfecf44876ca30d1bac7feb 

動態檔案快取成功!