WordPress在Nginx下的伪静态规则本身很简单:
location /
{
try_files $uri $uri/ /index.php?$args;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
但是安装插件WP Super Cache后需要301到静态文件目录,所以伪静态规则就要烦许多,尤其是配合子比模板这种第三方定制模板,摸索了半天才出来:
# ======================================================
# WordPress WP Super Cache + 子比主题优化伪静态规则
# 修复 try_files 重复错误 | 完全兼容 Nginx 1.26+
# ======================================================
# 核心缓存控制变量
set $supercache_skip 0;
# 动态请求排除条件
if ($request_method = POST) { set $supercache_skip 1; }
if ($query_string != "") { set $supercache_skip 1; }
if ($http_cookie ~* "(comment_author|wordpress_logged_in|wp_postpass|woocommerce_cart_hash)") {
set $supercache_skip 1;
}
# 子比主题动态路径排除
if ($request_uri ~* "(/user/|/pay/|/order/|/action/|/msg/|/credit/|/sign|/login|/register|/resetpass|/add-favorite|/like-post|/comment-upvote|/withdraw|/ajax\.php|/notifications)") {
set $supercache_skip 1;
}
# 主处理块 - 单一 try_files 指令
location / {
# 尝试提供超级缓存文件或回退到 WordPress
try_files /wp-content/cache/supercache/$http_host/$uri/index.html $uri $uri/ @nocache;
}
# 缓存跳过处理
location @nocache {
try_files $uri $uri/ /index.php?$args;
}
# ========================
# 增强功能配置
# ========================
# 静态资源长期缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp|woff2|woff|ttf)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 管理后台重定向
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# 安全设置 - 屏蔽敏感文件
location ~* (wp-config\.php|readme\.html|license\.txt|\.htaccess) {
deny all;
access_log off;
}
# 禁止访问隐藏文件
location ~ /\.(?!well-known) {
deny all;
access_log off;
log_not_found off;
}
# 防止缓存动态内容
location ~* (wp-admin|wp-login|user|pay|action|msg|ajax\.php) {
expires off;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
没有回复内容