
转载地址: WordPress安全加速:Cloudflare + Nginx缓存优化方案
在古代,驿站系统让信息传递快马加鞭,而今天,Cloudflare与Nginx的缓存优化,正是现代网站的“数字驿站”。本教程将带您配置静态资源长期缓存、动态页面智能缓存,以及敏感路径保护,让您的WordPress网站如离弦之箭,飞速加载。
✔ 域名托管于Cloudflare(橙色云代理开启)
✔ WordPress运行在OpenResty/Nginx(如1Panel面板)
✔ 已准备好服务器终端访问权限
目标:打造“静态资源保险库”——让CSS、JS、图片等静态资源长期缓存,减少重复请求。
在1Panel面板中,进入 网站 → 选择站点 → 配置文件(如nginx.conf) ,在server块内添加以下规则:
# 添加静态资源(CSS/JS/图片等)——365天缓存
location ~* .(css|js|png|jpg|jpeg|gif|ico|svg|webp|woff2)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
# 隐藏干扰头
proxy_hide_header Set-Cookie;
proxy_hide_header Pragma;
}
# 添加动态页面(首页/分类页/标签页)——10分钟缓存
location ~ ^/$|/page/|/category/|/tag/ {
add_header Cache-Control "public, max-age=600, stale-while-revalidate=300";
}
# 添加禁止缓存后台和敏感路径(如/wp-admin/)
location ~* ^/(wp-admin|wp-login|xmlrpc.php|my-account) {
add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 0;
}
# PHP请求处理(保持原有配置,仅添加缓存头)
location ~ [^/].php(/|$) {
fastcgi_pass 127.0.0.1:9000;
include fastcgi-php.conf;
include fastcgi_params;
# 添加缓存头-动态缓存控制
add_header Cache-Control "public, max-age=600";
}openresty -t && openresty -s reload效果:静态资源就像“图书馆的藏书”,适合长期缓存;动态页面就像“每日更新的报纸”,适合短时更新;后台路径则完全绕过缓存,确保安全。
Cloudflare的Cache Rules如同智能的“流量调度员”,让缓存策略更灵活,避免一刀切。
通过规则→概述→Cache Rules→创建规则,进入缓存规则创建界面

Cache Static Assets (http.request.uri.path contains "/wp-content/")
and
(http.request.uri.path ext in ("css" "js" "png" "jpg" "webp"))如果存在,使用缓存控制标头,如果不存在,使用 Cloudflare 的默认 TTL 缓存请求来获取响应状态。

Cache Dynamic Pages (http.request.uri.path in {"/" "/category/*" "/tag/*"})10分钟
Bypass Admin (http.request.uri.path contains "/wp-admin/")
or
(http.cookie contains "wordpress_logged_in")
curl -I https://yourDomain.com/wp-content/themes/YourTheme/style.css预期输出:
HTTP/2 200
CF-Cache-Status: HIT
Cache-Control: public, max-age=31536000, immutable curl -I https://yourDomain.com/可能结果:
CF-Cache-Status: HITCF-Cache-Status: DYNAMIC curl -I https://yourDomain.com/wp-admin/ --cookie "wordpress_logged_in=123"预期输出:
CF-Cache-Status: BYPASS
Cache-Control: no-storeCF-Cache-Status: DYNAMIC
解决:检查Cache Rules是否匹配目标路径CF-Cache-Status: BYPASS
解决:确认请求未携带Cookie或访问敏感路径
✅ 静态资源:1年缓存,减少90%请求\
✅ 动态页面:10分钟缓存,平衡实时性与速度\
✅ 后台路径:完全绕过缓存,确保安全

本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。