全面的针对nginx的wordpress rewrite规则

网上很多人都在找针对nginx的wordpress rewrite规则,找来找去,还是官方的比较标准,本服务器的配置同样参考于此,现摘抄过来,英文原帖请访问:http://codex.wordpress.org/Nginx

Main (generic) startup file (主要的启动脚本)

# Generic startup file.
user user {user} {group};
worker_processes  2;

error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

# Keeps the logs free of messages about not being able to bind().
#daemon     off;

events {
	worker_connections  1024;
}

http {
#	rewrite_log on;

	include mime.types;
	default_type       application/octet-stream;
	access_log         /var/log/nginx/access.log;
	sendfile           on;
#	tcp_nopush         on;
	keepalive_timeout  3;
#	tcp_nodelay        on;
#	gzip               on;
	client_max_body_size 13m;
	index              index.php index.html index.htm;

	# Upstream to abstract backend connection(s) for PHP.
	upstream php {
		server unix:/tmp/php-fpm.sock;
#		server 127.0.0.1:9000;
	}

	include sites-enabled/*;
}

Per Site configuration (站点配置文件)

# Redirect everything to the main site.
server {
	server_name *.mysite.com;
	root /var/www/mysite.com;

	if ($http_host != "mysite.com") {
		rewrite ^ http://mysite.com$request_uri permanent;
	}

	include global/restrictions.conf;

	// Additional rules go here.

	// Only include one of the files below.
	include global/wordpress.conf;
#	include global/wordpress-ms-subdir.conf;
#	include global/wordpress-ms-subdomain.conf;
}

Global restrictions file (全局限制文件)

# Global restrictions configuration file.
# Designed to be included in any server {} block.
location = /favicon.ico {
	log_not_found off;
	access_log off;
}

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

# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
location ~ /\. {
	deny all;
	access_log off;
	log_not_found off;
}

General WordPress rules (普通wordpress规则)

# WordPress single blog rules.
# Designed to be included in any server {} block.

# This order might seem weird - this is attempted to match last if rules below fail.
# http://wiki.nginx.org/HttpCoreModule
location / {
	try_files $uri $uri/ /index.php?$args;
}

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

# Directives to send expires headers and turn off 404 error logging.
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
	expires 24h;
	log_not_found off;
}

# Uncomment one of the lines below for the appropriate caching plugin (if used).
#include global/wordpress-wp-super-cache.conf;
#include global/wordpress-w3-total-cache.conf;

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ \.php$ {
	# Zero-day exploit defense.
	# http://forum.nginx.org/read.php?2,88845,page=3
	# Won't work properly (404 error) if the file is not stored on this server, which is entirely possible with php-fpm/php-fcgi.
	# Comment the 'try_files' line out if you set up php-fpm/php-fcgi on another machine.  And then cross your fingers that you won't get hacked.
	try_files $uri =404;

	fastcgi_split_path_info ^(.+\.php)(/.+)$;
	include fastcgi_params;
	fastcgi_index index.php;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#	fastcgi_intercept_errors on;
	fastcgi_pass php;
}

WordPress Multisite Subdirectory rules (多站点wordpress规则)

# WordPress multisite subdirectory rules.
# Designed to be included in any server {} block.

# This order might seem weird - this is attempted to match last if rules below fail.
# http://wiki.nginx.org/HttpCoreModule
location / {
	try_files $uri $uri/ /index.php?$args;
}

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

# Directives to send expires headers and turn off 404 error logging.
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
	expires 24h;
	log_not_found off;
}

# Pass uploaded files to wp-includes/ms-files.php.
rewrite /files/$ /index.php last;

# For multisite:  Use a caching plugin that creates symlinks to the correct subdirectory structure to get some performance gains.
set $cachetest "$document_root/wp-content/cache/ms-filemap/${host}${uri}";
if ($uri ~ /$) {
	set $cachetest "";
}
if (-f $cachetest) {
	# Rewrites the URI and stops rewrite processing so it doesn't start over and attempt to pass it to the next rule.
	rewrite ^ /wp-content/cache/ms-filemap/${host}${uri} break;
}

if ($uri !~ wp-content/plugins) {
	rewrite /files/(.+)$ /wp-includes/ms-files.php?file=$1 last;
}

# Uncomment one of the lines below for the appropriate caching plugin (if used).
#include global/wordpress-ms-subdir-wp-super-cache.conf;
#include global/wordpress-ms-subdir-w3-total-cache.conf;

# Rewrite multisite '.../wp-.*' and '.../*.php'.
if (!-e $request_filename) {
	rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
	rewrite ^/[_0-9a-zA-Z-]+.*(/wp-admin/.*\.php)$ $1 last;
	rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
}

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ \.php$ {
	# Zero-day exploit defense.
	# http://forum.nginx.org/read.php?2,88845,page=3
	# Won't work properly (404 error) if the file is not stored on this server, which is entirely possible with php-fpm/php-fcgi.
	# Comment the 'try_files' line out if you set up php-fpm/php-fcgi on another machine.  And then cross your fingers that you won't get hacked.
	try_files $uri =404;

	fastcgi_split_path_info ^(.+\.php)(/.+)$;
	include fastcgi_params;
	fastcgi_index index.php;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#	fastcgi_intercept_errors on;
	fastcgi_pass php;
}

WP Super Cache Rules (wordpress Super Cache 规则)

# WP Super Cache rules.
# Designed to be included from a 'wordpress-ms-...' configuration file.

# Enable detection of the .gz extension for statically compressed content.
# Comment out this line if static gzip support is not compiled into nginx.
gzip_static on;

set $supercacheuri "";
set $supercachefile "$document_root/wp-content/cache/supercache/${http_host}${uri}index.html";
if (-e $supercachefile) {
	set $supercacheuri "/wp-content/cache/supercache/${http_host}${uri}index.html";
}

# If this is a POST request, pass the request onto WordPress.
if ($request_method = POST) {
	set $supercacheuri "";
}

# If there is a query string, serve the uncached version.
if ($query_string) {
	set $supercacheuri "";
}

# Logged in users and those who have posted a comment get the non-cached version.
if ($http_cookie ~* comment_author_|wordpress_logged_in|wp-postpass_) {
	set $supercacheuri "";
}

# Mobile browsers get the non-cached version.
# Wastes CPU cycles if there isn't a mobile browser WP theme for the site.
if ($http_x_wap_profile) {
	set $supercacheuri "";
}

if ($http_profile) {
	set $supercacheuri "";
}

if ($http_user_agent ~* (2.0\ MMP|240x320|400X240|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|Googlebot-Mobile|hiptop|IEMobile|KYOCERA/WX310K|LG/U990|MIDP-2.|MMEF20|MOT-V|NetFront|Newt|Nintendo\ Wii|Nitro|Nokia|Opera\ Mini|Palm|PlayStation\ Portable|portalmmm|Proxinet|ProxiNet|SHARP-TQ-GX10|SHG-i900|Small|SonyEricsson|Symbian\ OS|SymbianOS|TS21i-10|UP.Browser|UP.Link|webOS|Windows\ CE|WinWAP|YahooSeeker/M1A1-R2D2|iPhone|iPod|Android|BlackBerry9530|LG-TU915\ Obigo|LGE\ VX|webOS|Nokia5800)) {
	set $supercacheuri "";
}

if ($http_user_agent ~* (w3c\ |w3c-|acs-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-|dang|doco|eric|hipt|htc_|inno|ipaq|ipod|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-|lg/u|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|wap-|wapa|wapi|wapp|wapr|webc|winw|winw|xda\ |xda-)) {
	set $supercacheuri "";
}

# Stop processing if the supercache file is valid.
if ($supercacheuri) {
	rewrite ^ $supercacheuri break;
}

链接规则结尾为/%post_id%/类似的改进:WP Super Cache规则

set $supercacheuri "";
set $supercachefile "$document_root/wp-content/cache/supercache/${http_host}${uri}/index.html";
if (-e $supercachefile) {
	set $supercacheuri "/wp-content/cache/supercache/${http_host}${uri}/index.html";
}

...

# Stop processing if the supercache file is valid.
if ($supercacheuri) {
	rewrite [^/]$ $scheme://$host$uri/ permanent;
	rewrite ^ $supercacheuri break;
}

A little more performance (演示)

< ?php
	require_once "wp-load.php";

	@ini_set('display_errors', 'On');
	nocache_headers();

	$blogs = $wpdb->get_results($wpdb->prepare("SELECT blog_id, domain, path FROM " . $wpdb->blogs . " WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' AND blog_id <> 1 AND last_updated <> '0000-00-00 00:00:00'", $wpdb->siteid));
	if ($blogs)
	{
		// Generate new symbolic links for uploaded files for each blog.
		foreach ($blogs as $blog)
		{
			$path = "/path/to/root/wp-content/cache/ms-filemap/" . $blog->domain;
			if (!is_dir($path))  @mkdir($path, 0777, true);
			$path .= $blog->path;
			$path = substr($path, 0, -1);
			if (!is_dir($path))  symlink("/path/to/root/wp-content/blogs.dir/" . $blog->blog_id . "/", $path);
		}
	}
?>

相关文章:

Leave a Reply