Nginx 是一種開源的高性能 Web 服務器,可用於加速內容和應用程序的交付。 Nginx 更安全,更具可擴展性,也可以用作高可用的負載均衡器。它可以用作反向代理,Nginx 最重要的用途之一是內容緩存。最好的方法之一是使用 Nginx 作為您的內容緩存。本文介紹 Nginx FastCGI 內容緩存以提高網站性能。

在 Nginx 中啟用 FastCGI 緩存

本文假設您在 Linux 機器上安裝了 Nginx 和 PHP。

要開始啟用 FastCGI 緩存,請編輯啟用緩存的虛擬主機配置文件。

$ cd /etc/nginx/conf.d
$ vi example.conf

將以下內容添加到文件頂部:線是 服務器{}指令.

fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=MYAPP:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

在哪裡,

  • fastcgi_cache_path – 緩存位置
  • 等級 – 緩存級別,在/etc/nginx/cache下設置2個目錄級別
  • 鍵盤 – 內存區域名稱(本例中我們使用了MYAPP,您可以隨意設置)
  • 不活躍 – 指定何時刪除在指定時間段內未被訪問的緩存數據。在此示例中,不活動時間設置為 60 米,但您可以增加或減少它。
  • fastcgi_cache_key – 指定如何散列緩存文件名

factcgi_cache_key 中使用的變量

  • $計劃 – 請求方案 HTTPS 或 HTTP
  • $request_method – 指定請求方法,例如 GET 或 POST
  • $主機 – 與請求匹配的服務器名稱
  • $request_uri – 完整的請求 URI

緩存文件的位置可以在硬盤上的任何位置,但大小應小於系統的 RAM + swap 以避免“無法分配內存”問題。

接下來,我們轉到 location 指令,它將 PHP 請求傳遞給 php-fpm。 將以下行添加到“location ~.php${}”

fastcgi_cache MYAPP;
fastcgi_cache_valid 200 1m;

其中 MYAPP 是內存區域名稱,fastcgi_cache_valid 200 緩存所有 HTTP 200 響應。

如果只定義了時間,200、301、302 響應將被緩存。

配置緩存持續時間

通過運行以下命令測試您的 Nginx 虛擬主機配置:

$ nginx -t

測試 nginx 配置語法

重啟 Nginx 服務。

$ systemctl restart nginx

一個完整的虛擬主機配置文件如下所示

fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=MYAPP:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

server {
  listen 80;
  root /usr/share/nginx/html;
  index index.php index.html index.htm;
  server_name your_server_name;
  location / {
    try_files $uri $uri/ /index.html;
  }
  location ~ .php$ {
    try_files $uri =404;
    fastcgi_pass unix:unix:/run/php/php8.0-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_cache MYAPP;
    fastcgi_cache_valid 200 60m;
  }
}

測試 FastCGI 緩存

在文檔根目錄中創建一個簡單的 PHP 文件。

$ vi /usr/share/nginx/html/info.php

粘貼以下內容並保存

<?php
phpinfo();
?>

使用 curl 命令或瀏覽器請求文件。

如果緩存是健康的,你可以列出 /etc/nginx/cache 下的緩存目錄。

測試 nginx 緩存

在 server{} 指令上方添加以下行以指示是否存在緩存未命中或命中。

add_header X-Cache $upstream_cache_status;

重新啟動 Nginx 並運行 curl 命令,如下所示:

$ curl -I https://localhost/info.php

高速緩存命中

使用 Nginx fastCGI Cache 配置緩存異常

在某些情況下,您可能不需要緩存動態內容,例如基本身份驗證頁面。這些類型的內容可以避免基於“$request_method”、“$request_uri”、“$http_cookie”等各種變量的緩存。

下面是一個設置緩存異常的例子。這應該使用 {} 在服務器內部使用。

指導。

#Cache everything by default

set $no_cache 0;

#Don't cache POST requests
if ($request_method = POST)
{
set $no_cache 1;
}


#Don't cache if the URL contains a query string
if ($query_string != "")
{
set $no_cache 1;
}


#Don't cache the following URLs
if ($request_uri ~* "/(cp/)")
{
set $no_cache 1;
}

#Don't cache if there is a cookie called PHPSESSID
if ($http_cookie = "PHPSESSID")
{
set $no_cache 1;
}

結論是

在本文中,您學習瞭如何使用 PHP 配置 Nginx 以實現動態內容緩存。我還看到了設置緩存異常的不同技術。