nginx下WP的url rewrite

nginx可以像apache那样支持htaccess来实现rewrite,但实际上htaccess需要对文件夹内每个文件进行一次判断来实现重写,效率并不高。

nginx在站点配置文件中的location /{………………}里面加入
if (!-f $request_filename){
rewrite (.*) /index.php;
}

即可实现。
这里安利两种方式,可自行取用
1.rewrite方式

server {
listen 80;
server_name yoursite.com www.yoursite.com;
location / {
index index.html index.htm index.php;
root /www/wwwroot/yoursite.com;
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 ~ \.php$ {
include fastcgi_params;
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:8787;
fastcgi_param SCRIPT_FILENAME /www/wwwroot/yoursite.com$fastcgi_script_name;
}
location /ccvita-status {
stub_status on;
access_log off;
}
}

或者:

server
{
server_name .example.com;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
root /var/www/example.com/html;
index index.php index.html index.htm;
# enforce www (exclude certain subdomains)
#if ($host !~* ^(www|subdomain))
#{
# rewrite ^/(.*)$ $scheme://www.$host/$1 permanent;
#}
# enforce NO www
if ($host ~* ^www\.(.*))
{
set $host_without_www $1;
rewrite ^/(.*)$ $scheme://$host_without_www/$1 permanent;
}
# unless the request is for a valid file, send to bootstrap
if (!-e $request_filename)
{
rewrite ^(.+)$ /index.php?q=$1 last;
}
# catch all
error_page 404 /index.php;
# use fastcgi for all php files
location ~ \.php$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/example.com/html$fastcgi_script_name;
include fastcgi_params;
}
# deny access to apache .htaccess files
location ~ /\.ht
{
deny all;
}
}

以上可以强制加www或者不加www,改为二级域名转向也可以

# unless the request is for a valid file, send to bootstrap
if (!-e $request_filename)
{
rewrite ^(.+)$ /index.php?q=$1 last;
}

2.try_files 方式

server {
## Your website name goes here.
server_name domain.tld;
## Your only path reference.
root /var/www/wordpress;
## This should be in your http block and if it is, it's not needed here.
index index.php;

location = /favicon.ico {
log_not_found off;
access_log off;
}

location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}

location / {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
#NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
include fastcgi.conf;
fastcgi_intercept_errors on;
fastcgi_pass php;
}

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}

安装在子目录下时候:

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

location ~ \.php$ {
        fastcgi_split_path_info ^(/wordpress)(/.*)$;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据