Apache和Nginx下WordPress的Rewrite规则

Apache

在Apache下,利用mod_rewrite来实现URL的静态化。

.htaccess的内容如下:
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

Nginx

方法一:在Nginx下配置WordPress的Rewrite还是比较简单的,在location /{………………}里面加入如下代码即可实现

if (!-e $request_filename){
rewrite (.*) /index.php;
}

下面是一个完整的vhost的配置文件,可以参考一下

server {
listen 443 ssl;
listen [::]:443 ssl;
ssl_certificate /etc/nginx/ssl/XXXX.pem;
ssl_certificate_key /etc/nginx/ssl/XXXX.key;
server_name www.XXXX.com;
root /var/www/html/XXX;
index index.html index.htm index.php;
charset utf-8;

location ~ \.php$ {
include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}

location ~ /var-.* {
deny all;
return 404;
}

if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}

location / {
try_files $uri $uri/ /index.php?$args;
}

# Add trailing slash to */wp-admin requests.
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
}

方法二:Nginx的另外一种实现方法:

1.如果WordPress装在网站的根目录下,或者你配置了虚拟目录指向网站域名的根路径,你需要在”location / { }”内加入以下配置
if (!-e $request_filename) {
rewrite (.*) /index.php;
}

2.如果WordPress装在网站的子目录下,比如”http://域名/wordpress/”。这时,你需要在”server { }”内加入
location /wordpress/ {
if (!-e $request_filename) {
rewrite (.*) /wordpress/index.php;
}
}

注意,两者的主要区别在于重写的路径中加了”/wordpress”。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注