Apache 透過 SetEnvIf 系列指令以正則比對請求特徵設定環境變數,再搭配 CustomLog、Allow/Deny 實現條件存取控制、日誌記錄、盜鏈防護。
# 不分大小寫比對 Request_URI 開頭為 /aslibra
SetEnvIfNoCase Request_URI "^/aslibra" IS_START=1
# 針對常見靜態副檔名設定 NOLOG=1
SetEnvIfNoCase Request_URI "\.(gif|jpg|jpeg|png|css|js|ico|woff|woff2)$" NOLOG=1
# 日誌指令排除 NOLOG=1 的請求
CustomLog logs/access_log combined env=!NOLOG
SetEnvIfNoCase Request_URI "^/aslibra" IS_START=1
CustomLog "|/usr/local/sbin/cronolog /var/log/httpd/%Y/%m/%d/aslibra.%Y%m%d%H.log" combined env=IS_START
# 允許自有域名與 localhost
SetEnvIfNoCase Referer "^https?://(www\.)?mydomain\.com/" LOCAL_REF=1
SetEnvIfNoCase Referer "^https?://127\.0\.0\.1/" LOCAL_REF=1
Order Allow,Deny
Allow from env=LOCAL_REF
# 可選:拒絕時回傳預設圖片
# ErrorDocument 403 /images/hotlink-denied.png
SetEnvIfNoCase Referer "^https?://bad\.domain\.com/" BAD_REF=1
Order Allow,Deny
Allow from all
Deny from env=BAD_REF
# 允許空 Referer (直接訪問)
SetEnvIf Referer "^$" ALLOW_EMPTY_REF=1
Order Allow,Deny
Allow from env=LOCAL_REF
Allow from env=ALLOW_EMPTY_REF
# CentOS/RHEL
yum install cronolog
# Debian/Ubuntu
apt-get install cronolog
# 原始碼編譯
./configure --prefix=/usr/local && make && make install
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# 自訂格式:含 Cookie、精確時間
LogFormat "%h %{YYYY-MM-dd'T'HH:mm:ss}t \"%r\" %{SESSIONID}C" detailed
# 主站綜合日誌
CustomLog "|/usr/local/sbin/cronolog /var/log/httpd/main/%Y/%m/%d/access.%Y%m%d%H.log" combined
# 特定應用條件日誌
SetEnvIfNoCase Request_URI "^/api/" IS_API=1
CustomLog "|/usr/local/sbin/cronolog /var/log/httpd/api/%Y/%m/%d/api.%Y%m%d%H.log" combined env=IS_API
# 錯誤日誌同樣可切割
ErrorLog "|/usr/local/sbin/cronolog /var/log/httpd/error/%Y/%m/%d/error.%Y%m%d%H.log"
/var/log/httpd/*/*.log {
daily
missingok
rotate 90
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
/bin/systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
a2dismod autoindex status cgi userdir 等LimitRequestBody 10485760 (10MB)ServerTokens Prod、ServerSignature OffProtocols h2 http/1.1 (需 SSL)mpm_event_module + ThreadLimit/ThreadsPerChild 調優mod_expires、mod_headers 設定靜態資源長期快取、ETag 調整