X-Cache 改為 Powered-By-ChinaCache,作為服務標識。Squid 原始碼中,HttpHeader 類負責構建回應標頭。關鍵檔案:
src/HttpHeader.cc(或舊版 HttpHeader.c)HttpHeader::putStrf() / HttpHeader::addEntry() 處理 HDR_X_CACHE / HDR_X_CACHE_LOOKUP 列舉值。# 方式一:系統套件源(含 debuginfo/源碼 RPM)
yum install -y yum-utils
yumdownloader --source squid
rpm2cpio squid-*.src.rpm | cpio -idmv
# 方式二:官方發布頁下載 tarball
wget https://www.squid-cache.org/Versions/v5/squid-5.9.tar.xz
tar -xJf squid-5.9.tar.xz
# 搜尋關鍵字
grep -rn "X-Cache" src/
# 典型位置:src/HttpHeader.cc, src/HttpReply.cc, src/ForwardClient.cc
# 編輯 src/HttpHeader.cc(示例)
vi src/HttpHeader.cc
# 找到類似:
# static const char *x_cache_str = "X-Cache";
# static const char *x_cache_lookup_str = "X-Cache-Lookup";
# 修改為:
static const char *x_cache_str = "X-Cache-Custom";
static const char *x_cache_lookup_str = "X-Cache-Lookup-Custom";
# 或直接修改格式化字串(視版本而定)
# 例:mb->Printf("X-Cache: %s from %s", hit?"HIT":"MISS", ThisCache);
# 改為:
# mb->Printf("X-Powered-By: MyCDN %s from %s", hit?"HIT":"MISS", ThisCache);
cd squid-5.9
./configure --prefix=/usr/local/squid \
--enable-http-violations \
--enable-ssl-crtd \
--with-openssl \
...(其餘參數保持原編譯參數一致)
make -j$(nproc)
make install
systemctl stop squid
cp /usr/local/squid/sbin/squid /usr/sbin/squid # 或依原安裝路徑替換
systemctl start squid
curl -I https://proxy.example.com/test.jpg
# 預期輸出:
# X-Cache-Custom: HIT from proxy01
# X-Cache-Lookup-Custom: HIT from proxy01:3128
header_replace / header_access(Squid 3.2+)# 隱藏原有 X-Cache
header_access X-Cache deny all
header_access X-Cache-Lookup deny all
# 注入自定義標頭(需啟用 http_violations)
header_replace X-Cache-Custom "HIT from MyCDN"
# 注意:此處無法動態區分 HIT/MISS,僅靜態字串
缺點:無法保留 HIT/MISS 動態資訊,失去緩存狀態可觀測性。
reply_header_access + 外部腳本(進階)透過 external_acl_type 呼叫腳本動態生成標頭,複雜度高,通常不建議。
# Nginx 範例(作為 Squid 前置邊緣)
location / {
proxy_pass https://squid_backend;
proxy_hide_header X-Cache;
proxy_hide_header X-Cache-Lookup;
add_header X-Cache-Status $upstream_http_x_cache; # 透傳並重命名
add_header X-Powered-By "MyCDN/1.0";
}
優勢:不動 Squid 核心,邊緣層統一治理標頭,支援動態變量、條件判斷、WAF 整合。
| Squid 版本 | 關鍵檔案 | 備註 |
|---|---|---|
| 2.6 / 2.7 | src/HttpHeader.c, src/HttpReply.c | 舊版 C 風格,字串定義較分散 |
| 3.0 ~ 3.5 | src/HttpHeader.cc, src/HttpReply.cc | C++ 重寫,列舉 HDR_X_CACHE 定義於 HttpHeaderSym.cca |
| 4.x / 5.x / 6.x | src/HttpHeader.cc, src/HttpReply.cc, src/ForwardClient.cc | 模組化重構,HttpHeader 為核心,搜尋 X-Cache 即可定位 |
# squid.conf 建議配置
header_access Server deny all # 隱藏 Server: squid/x.x
header_access X-Squid-Error deny all # 隱藏錯誤頁標頭
header_access Via deny all # 隱藏 Via 代理鏈(或保留合規需求)
header_replace Via "1.1 MyCDN" # 替換為品牌標識
# 錯誤頁面自定義(避免預設錯誤頁洩露版本/路徑)
error_directory /usr/local/squid/share/errors/Custom
# 編輯錯誤模板移除版本資訊
修改 X-Cache 標頭可通過原始碼重編譯(保留動態 HIT/MISS)或邊緣層 Nginx 改寫(運維彈性大)實現。生產環境建議採用邊緣層統一治理:Squid 專注緩存邏輯,Nginx/Envoy 負責標頭清洗、品牌注入、安全加固,職責分離,升級無憂。