一、安装 Nginx Helper 插件
Nginx Helper 插件可以帮助我们自动生成 Nginx map 映射关系,这有利于接下来配置 Nginx 伪静态规则。安装并在站点网络启用此插件,然后在插件设置页面勾上Enable Nginx Map.
选项保存,即可看到插件为我们生成的映射关系文件信息。

二、修改网站配置文件
以宝塔面板为例,在网站配置文件server
区域上方添加下方代码,并修改引入 Nginx Helper 插件生成的映射关系文件。
这是子目录的:
map $uri $blogname {
~^(?<blogpath>/[^/]+/)files/(.*) $blogpath ;
}
map $blogname $blogid {
default -999;
include 映射文件路径.conf;
}
这是子域名的:
map $http_host $blogid {
default -999;
include 映射文件路径.conf;
}
保存完成后应如下图所示:

三、设置 Nginx 伪静态规则
还是以宝塔面板为例,打开网站的伪静态配置页面,输入下方代码:
这是子目录的:
# 避免 PHP 读取静态文件
location ^~ /blogs.dir {
internal;
alias /网站目录/wp-content/blogs.dir ;
access_log off; log_not_found off; expires max;
}
# 通过 map 读取对应站点的文件
location ~ ^(/[^/]+/)?files/(.+) {
try_files /wp-content/blogs.dir/$blogid/files/$2 /wp-includes/ms-files.php?file=$2 ;
access_log off; log_not_found off; expires max;
}
# 重写
if (!-e $request_filename) {
rewrite /wp-admin$ $scheme://$host$request_uri/ permanent;
rewrite ^(/[^/]+)?(/wp-.*) $2 last;
rewrite ^(/[^/]+)?(/.*\.php) $2 last;
}
# 重写
location / {
try_files $uri $uri/ /index.php?$args ;
}
这是子域名的:
# 避免 PHP 读取静态文件
location ^~ /blogs.dir {
internal;
alias /网站目录/wp-content/blogs.dir ;
access_log off; log_not_found off; expires max;
}
# 通过 map 读取对应站点的文件
location ~ ^/files/(.*)$ {
try_files /wp-content/blogs.dir/$blogid/$uri /wp-includes/ms-files.php?file=$1 ;
access_log off; log_not_found off; expires max;
}
# 重写
location / {
try_files $uri $uri/ /index.php?$args ;
}
四、大功告成
如果你有使用 WP-Super-Cache 或者 W3 Total Cache ,可前往https://wordpress.org/support/article/nginx/#wp-super-cache-rules以获取它们所使用的 Nginx 规则,替换上述规则相应的部分,这将使缓存绕过PHP以达到性能最大化。
文章评论