Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Varnish Cache 清除機制完整教學:PURGE 指令、正則匹配、管理介面與 PHP 介接

編輯:Linux 教學

兩種清除模式

模式一:強制過期 - 單一變體清除

僅清除命中的具體物件變體(如未壓縮版本),無法同時清除 gzip 版本。


acl purge { "localhost"; "192.0.2.14"; }

sub vcl_recv {
    if (req.request == "PURGE") {
        if (!client.ip ~ purge) { error 405 "Not allowed."; }
        lookup;
    }
}
sub vcl_hit {
    if (req.request == "PURGE") { set obj.ttl = 0s; error 200 "Purged."; }
}
sub vcl_miss {
    if (req.request == "PURGE") { error 404 "Not in cache."; }
}

模式二:purge_url - 支援正則與多變體


acl purge { "localhost"; "192.0.2.14"; }

sub vcl_recv {
    if (req.request == "PURGE") {
        if (!client.ip ~ purge) { error 405 "Not allowed."; }
        purge("req.url == " req.url);      # 精確匹配
        # purge("req.url ~ " req.url);     # 正則匹配
    }
}

HTTP 觸發範例


PURGE / HTTP/1.0
Host: www.example.com

送至 Varnish 80 port 即可觸發。

管理介面 (CLI) 彈性清除

連線


telnet 192.168.1.185 3500
# 或
varnishadm -T 192.168.1.185:3500

指令對照

指令用途範例
purge.url <regexp>URL 正則清除purge.url ^test.html$
purge <field> <op> <arg> [&& ...]多條件彈性清除purge req.http.host == izhoufeng.com && req.url ~ ^/somedirectory/.*$
purge.list列出待清除規則—

進階範例

  • 清除整個目錄:purge req.url ~ ^/somedirectory/ && req.http.host == izhoufeng.com
  • 清除特定 Cache-Control:purge obj.http.Cache-Control ~ max-age=3600

大量清除程式化介接

PHP 透 HTTP PURGE


function varnish_purge($ip, $host, $url) {
    $fp = fsockopen($ip, 80, $errno, $errstr, 5);
    if (!$fp) return false;
    $request = "PURGE $url HTTP/1.0\r\nHost: $host\r\n\r\n";
    fwrite($fp, $request);
    fclose($fp);
    return true;
}

PHP 透管理介面


function varnish_adm_purge($mgmt_ip, $mgmt_port, $regex) {
    $fp = fsockopen($mgmt_ip, $mgmt_port, $errno, $errstr, 5);
    if (!$fp) return false;
    fwrite($fp, "purge.url $regex\n");
    fclose($fp);
    return true;
}
Copyright © Windows教程網 All Rights Reserved