Select Page

Nginx Cache:fastcgi_cache purging (NGINX Helper)使用教學

Nginx 是一個高效能、高穩定性的 Web 伺服器。其中,Nginx 提供的 fastcgi_cache 可以有效地快取後端伺服器(如 PHP-FPM)的回應,以提高網站的回應速度。但在預設情況下,我們需要手動清理這些快取。此時,我們可以使用 NGINX Helper 插件來協助進行快取的清除。

前期準備

要有編譯器

sudo apt-get install g++

NGINX Helper

1. 安裝 NGINX Helper

首先,你需要在你的網站上安裝 NGINX Helper。如果你使用的是 WordPress,可以直接從插件庫中安裝。

2. 設定 NGINX 快取路徑

為了讓 NGINX Helper 知道你的 Nginx 快取路徑,你需要在 Nginx 的設定檔中,指定 fastcgi_cache_path。例如:

fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=MYCACHE:100m inactive=60m;

此設定將會在 /var/run/nginx-cache 建立快取資料。

3. 配置 NGINX Helper

在 WordPress 的設定中,找到 NGINX Helper 的設定頁面,並啟用以下選項:

  • Enable Cache Purge
  • Purge Entire Cache when a post or page is published

並設定你的 Nginx 快取路徑(如 /var/run/nginx-cache)。

4. 手動清除快取

若需要手動清除快取,可以直接在 NGINX Helper 的設定頁面點選 “Purge Entire Cache” 按鈕。

5. Nginx 設定更新

確保你的 Nginx 設定檔有啟用快取清除功能:

location ~ /purge(/.*) { fastcgi_cache_purge MYCACHE "$scheme$request_method$host$1"; }

6.重新加載 Nginx 以使新設定生效。Copy code

sudo systemctl reload nginx

安裝 Nginx 新版包含有ngx_cache_purge

1.備份配置

在進行任何更改之前,確保備份你當前的 Nginx 配置,以防止任何數據丟失。

sudo cp -r /etc/nginx /etc/nginx-backup

停止和卸載現有的 Nginx

首先,停止 Nginx 服務:

sudo systemctl stop nginx

然後,卸載 Ubuntu 的 Nginx 版本:

sudo apt-get purge nginx nginx-common nginx-full

下載 OpenSSL

wget -c https://www.openssl.org/source/openssl-3.0.11.tar.gz ; tar zxf openssl-3.0.11.tar.gz ; rm openssl-3.0.11.tar.gz

下載第三方模組

安裝 ngx_cache_purge

下載最新版本 https://github.com/nginx-modules/ngx_cache_purge/releases

wget https://github.com/nginx-modules/ngx_cache_purge/archive/refs/tags/2.5.3.tar.gz
tar -xvzf 2.5.3.tar.gz

ngx_brotli

git clone https://github.com/google/ngx_brotli.git
pushd ngx_brotli
git submodule update --init
popd

編譯 ngx_brotli

cd ~/ngx_brotli/deps/brotli/c
mkdir -p out
cmake ..
make

編譯和安裝 Nginx 1.2

如果你還沒有下載和編譯 Nginx 1.2,首先下載源代碼,然後編譯和安裝它:

sudo apt-get update
sudo apt-get install libpcre3 libpcre3-dev

wget https://nginx.org/download/nginx-1.24.0.tar.gz 

tar -xvzf nginx-1.24.0.tar.gz

cd nginx-1.24.0/

./configure --with-pcre=../pcre-8.45 \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-openssl=../openssl-3.0.11 \
--add-module=../ngx_brotli \
--add-module=../ngx_cache_purge-2.5.3 

make

sudo make install

預設情況下,自行編譯的 Nginx 會被安裝到 /usr/local/nginx

如果出現下面的錯誤

./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

代表你apt-get install libpcre3 libpcre3-dev這邊出現問題

可以自行安裝 PCRE

wget https://ftp.exim.org/pub/pcre/pcre-8.45.tar.gz
tar -xvzf pcre-8.45.tar.gz

./configure --with-pcre=../pcre-8.45 \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-openssl=../openssl-3.0.11 \
--add-module=../ngx_brotli \
--add-module=../ngx_cache_purge-2.5.3 

如果出現gzip錯誤

./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.

那可以自行安中 zlib

sudo apt-get update
sudo apt-get install zlib1g zlib1g-dev

如果出現 cannot find -lbrotlienc or cannot find -lbrotlicommon ,那需要安裝 Brotli

sudo apt update
sudo apt install libbrotli-dev

驗證 Brotli 是否安裝成功

ldconfig -p | grep brotli

檢查安裝是否成功

sudo /usr/local/nginx/sbin/nginx -V

配置系統啟動腳本

如果你希望 Nginx 在系統啟動時自動運行,你需要設置一個 systemd 服務文件或 init 腳本。由於你從源代碼編譯 Nginx,它不會自帶 systemd 服務文件,所以你可能需要自行創建。

恢復配置

從你之前備份的配置恢復設置:

sudo cp -r /etc/nginx-backup/* /usr/local/nginx/conf/

請注意,由於 Nginx 版本之間可能存在差異,所以你可能需要調整配置以使其與 Nginx 1.2 版本兼容。

啟動新的 Nginx

sudo /usr/local/nginx/sbin/nginx

要使 /usr/local/nginx/sbin/nginx 可在任何地方都能執行

使用符號鏈接

你可以在 /usr/bin/usr/sbin 中創建一個指向 /usr/local/nginx/sbin/nginx 的符號鏈接。這樣,由於 /usr/bin/usr/sbin 通常都在 $PATH 環境變量中,你就可以從任何地方執行 nginx 命令。

sudo ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx

修改 $PATH 變量

作為另一種方法,你可以將 /usr/local/nginx/sbin 目錄添加到 $PATH 環境變量中。這可以在你的 shell 啟動腳本中完成,例如 ~/.bashrc~/.profile。打開 ~/.bashrc 文件:

nano ~/.bashrc

在文件末尾添加以下行:

export PATH=$PATH:/usr/local/nginx/sbin

然後,重新加載 .bashrc 以應用更改:

source ~/.bashrc

管理 Nginx

你可以直接從GitHub下載nginx-startup-script-for-debian-ubuntu.sh至你的『/etc/init.d』目錄,並將名稱更改為『nginx』。

sudo wget -O /etc/init.d/nginx https://raw.githubusercontent.com/KJieGitHub/Nginx/master/nginx-script/nginx-startup/nginx-startup-script-for-debian-ubuntu.sh
sudo chmod +x /etc/init.d/nginx
sudo systemctl daemon-reload
sudo systemctl start nginx
sudo update-rc.d -f nginx defaults

實用管理命令

sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx

實用連結

Nginx 版本以及下載連結

https://nginx.org/en/download.html

Nginx 第三方模組

NGINX 3rd Party Modules

參考資料

https://www.kjnotes.com/devtools/83

https://github.com/FRiCKLE/ngx_cache_purge

完整版本的 Nginx Config

proxy_cache_path /var/run/proxy_cache/ levels=1:2 keys_zone=demo-proxy:10m max_size=1000m inactive=600m use_temp_path=off;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

server {
		listen 80;
        server_name yoursite;

        proxy_cache demo-proxy;
        proxy_cache_valid 200 1d;
        
        #設定上傳的檔案大小
        client_max_body_size 64M;

        set $skip_cache 0;
        add_header X-Cache $upstream_cache_status;

        if ($request_method = POST) {
            set $skip_cache 1;
        }

        if ($query_string != "") {
            set $skip_cache 1;
        }

        if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|^/feed/*|/tag/.*/feed/*|index.php|/.*sitemap.*\.(xml|xsl)") {
            set $skip_cache 1;
        }

        if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+wp-postpass|wordpress_no_cache|wordpress_logged_in") {
            set $skip_cache 1;
        }

        location / {
                proxy_cache_bypass $skip_cache;
                proxy_no_cache $skip_cache;

                proxy_hide_header X-Frame-Options;
                proxy_pass http://X.X.X.X:X;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_cache        demo-proxy;
                proxy_cache_key    $uri$is_args$args;

        }

    location ~ /purge(/.*) {
        allow 127.0.0.1; 
        proxy_cache_purge  demo-proxy $1$is_args$args;
    }
}
Redis提升WP性能:一步步教您如何優化安裝與配置Redis資料庫

Redis提升WP性能:一步步教您如何優化安裝與配置Redis資料庫

Redis作為一款開源的高性能key-value數據庫,已經在眾多頂尖科技公司和網站獲得廣泛應用。本文將引領您走過安裝和配置Redis資料庫的過程,並提供實用的優化技巧,助力您的系統性能達到新的高峰。

為什麼選擇Redis?

首先,讓我們理解一下為什麼您應該選擇Redis。Redis以其極速性能、靈活的數據結構和高可用性成為獨一無二的選擇。它可以作為緩存,消息佇列,以及在高壓情況下用作可靠的數據存儲。

安裝Redis

Ubuntu安裝Redis

sudo apt install redis-server

Windows 安裝 Redis

直接下載微軟製作的安裝包,下載網址 https://github.com/MicrosoftArchive/redis/releases

驗證Redis是否安裝成功

如果是剛安裝好,並且在同一台機器上可以直接打指令 redis-cli 就可以連線

redis-cli
redis-cli ping
redis-cli info

如果是別台機器的話,記得要開防火牆,並且指定 IP 以及指定 Port 和指定密碼

redis-cli -h 192.168.0.X -p 6379 -a 123456

設定Redis

  • bind:若要遠端連入Redis伺服器,就會需要設定 bind 0.0.0.0 ::
  • databases:設定可用的資料庫數量,在索引的時候是從0開始數,預設會使用索引值為0的資料庫。這個項目的預設值是16
  • save:設定在一定的間隔時間內若資料庫有發生一定程度的改變,就將記憶體中當下的資料存成檔案(快照)。save的撰寫格式為save <seconds> <changes>save 60 10000表示在60秒內至少有10000個key被改變則做一次快照。
  • requirepass:設定客戶端與Redis伺服器連線時所需要的密碼。預設沒有設定,表示不啟用密碼驗證功能。
  • maxclients:設定最大連線數。預設沒有設定,當作10000
  • maxmemory:設定最大的記憶體使用量,如果記憶體用量達到限制,就會根據maxmemory-policy項目設定的策略來嘗試移除key,如果無法移除,就會使該次插入或修改的操作回傳錯誤。預設沒有設定,表示不限制。
  • maxmemory-policy:記憶體用量達到限制時採取的策略。預設沒有設定,當作noeviction,不移除key。其它策略如下:
    • volatile-lru:根據LRU演算法移除過期的key。
    • allkeys-lru:根據LRU演算法移除key。(不管有沒有過期)
    • volatile-lfu:根據LFU演算法移除過期的key。
    • allkeys-lfu:根據LFU演算法移除key。(不管有沒有過期)
    • volatile-random:隨機移除過期的key。
    • allkeys-random:隨機移除key。(不管有沒有過期)
    • volatile-ttl:移除已過期的key中,TTL最小的key。

清除Redis的資料

利用 redis-cli 進去 Redis 主機後,輸入

flushall

清除單一資料的指令是

flush db0

在 WordPress 中使用 Redis

Redis Object Cache 外掛網址 https://wordpress.org/plugins/redis-cache/

設定 wp-config.php

// adjust Redis host and port if necessary 
define( 'WP_REDIS_HOST', '127.0.0.1' );
define( 'WP_REDIS_PORT', 6379 );

// change the prefix and database for each site to avoid cache data collisions
define( 'WP_REDIS_PREFIX', 'my-moms-site' );
define( 'WP_REDIS_DATABASE', 0 ); // 0-15

// reasonable connection and read+write timeouts
define( 'WP_REDIS_TIMEOUT', 1 );
define( 'WP_REDIS_READ_TIMEOUT', 1 );

/* That's all, stop editing! Happy publishing. */
require_once(ABSPATH . 'wp-settings.php');

組態檔

Configuration constantDefaultDescription
WP_REDIS_HOST127.0.0.1The hostname of the Redis server
WP_REDIS_PORT6379The port of the Redis server
WP_REDIS_PATHThe path to the unix socket of the Redis server
WP_REDIS_SCHEMEtcpThe scheme used to connect: tcp or unix
WP_REDIS_DATABASE0The database used by the cache: 0-15
WP_REDIS_PREFIXThe prefix used for all cache keys to avoid data collisions, replaces WP_CACHE_KEY_SALT. Should be human readable, not a “salt”.
WP_REDIS_PASSWORDThe password of the Redis server. Supports Redis ACLs arrays: ['user', 'password']
WP_REDIS_MAXTTL0The maximum time-to-live of cache keys
WP_REDIS_CLIENTThe client used to communicate with Redis: predisphpredis or relay
WP_REDIS_TIMEOUT1The connection timeout in seconds
WP_REDIS_READ_TIMEOUT1The timeout in seconds when reading/writing
WP_REDIS_IGNORED_GROUPS[]Groups that should not be cached between requests in Redis

常用控制指令

CommandDescription
wp redis statusShows the object cache status and diagnostics
wp redis enableEnables the object cache
wp redis disableDisables the object cache
wp redis update-dropinUpdates the object cache drop-in

關於Redis的大小事

預設安裝完畢,初始話是支援16個資料庫的,分別由編號 0-15 ,要增加資料庫,要去 Redis 的組態檔裡面修改 redis/redis.conf 中,找到 databases ,並且調整數值後,重新啟動即可

databases 16

Redis 讀取資料

redis-cli set my_key "Value"
redis-cli get my_key

Redis 列出所有的 KEY

redis-cli KEYS *

相關文章

詳細的指令操作介紹

iis web 將 http 協定導引成 https 協定(http to https)

iis web 將 http 協定導引成 https 協定(http to https)

現在的網站一定都要有https的協定才會是安全的,SEO的分數也才會高,在IIS內可以直接透過 URL rewrite 來將 http 連線都轉換成 https 連線,過程比 nginx 要麻煩一點,但有圖形化的介面設定,也是蠻容易上手的

打開 IIS Manager 找到 URL Rewrite

先假設你已經完成了 URL Rewrite 的安裝,則可以在介面中看到 URL Rewrite的設定

建立新的規則 (Add Rule)

在右邊的 Actions 選擇 Add Rule(s),並且選擇 Blank rule

建立 Inbound Rule

如下圖,下拉方塊中選擇 Match URL,並且在 Pattern 中填入 (.*) ,然後移到下方 Conditions 選擇 Add

並且在 Condition input 填入 {HTTPS} ,在 Pattern 中填入 ^OFF$ ,下拉選單中則是選擇 Matches the Pattern

設定 Action

輸入網址的條件設定完之後,要來設定符合的網址要如何處理,如何做動作,參考下圖,Action type 的下拉選單,選擇 Redirect

並且在 Redirect URL 中,填入 https://{HTTP_HOST}/{R:1} ,並且到 Redirect type 下拉選單中選擇 Permanent(301) 後即可以存檔 (Apply)

Web.Config 中的 rewrite

用 iis manager 設定完畢後,你就可以在 web.config 中看到剛剛所做的設定

        <rewrite>
            <rules>
                <clear />
                <rule name="http2https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
                </rule>
            </rules>
        </rewrite>

參考資料

https://aboutssl.org/iis-redirection-http-to-https/