• 赤色のリンクは、まだ日本語Codexに存在しないページ・画像です。英語版と併せてご覧ください。(詳細

このWikiはいつでも誰でも編集できます

Nginx

提供: WordPress Codex 日本語版
2011年8月31日 (水) 01:30時点におけるShinichiN (トーク | 投稿記録)による版 (en: Nginx 19:34, 11 August 2011 Plugpress,Bigsite,PaBLoX,Zupolgec,C3mdigital)

(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
移動先: 案内検索
このページ「Nginx」はまだ書きかけで、情報が不足しています。続きを書いて WordPress を手助けしましょう.


While the LAMP stack is very popular (Linux + Apache + MySQL + PHP) for powering WordPress, a lot of people have started using nginx in place of Apache. This page aims to help those looking to configure WordPress with nginx.

Before you consider using nginx, be aware that PHP APC or a similar opcode cache with a WordPress caching plugin is going to offer significant performance improvements over just switching from Apache to nginx. If you aren't already using a PHP opcode cache and WordPress caching plugin, nginx will do squat for your WordPress-based website's performance. Also, WordPress is intertwined with the Apache world so support for nginx-based setups is limited but growing. Factor these things into your decision to use nginx.

This is not going to cover how to install and configure Nginx, so this assumes you already installed it and have a basic understanding of how to work with it.

Note: This has been tested on and known to work with:

  • Arch Linux 64 bit (nginx 0.8.54)
  • Mac OSX Server Leopard and OSX Server Snow Leopard via MacPorts (nginx 0.8.54, php-fpm support requires modifying the PHP 5.3 'Portfile')
  • Ubuntu Server 10.04 LTS (nginx 0.8.54 with php-fpm)


Generic and Network (Multi-Site) Support

To make WordPress work with Nginx you have to configure the backend php-cgi. The options available are 'fastcgi' or 'php-fpm'. Here I'm using php-fpm because it is supposed to be better and it is also included in PHP 5.3, so installing it is more straightforward.

The nginx configuration has been broken up into five distinct files and it's heavily commented to make each option easier to understand. The author also made a best-effort attempting to follow "best practices" for nginx configurations.

Main (generic) startup file

This is equivalent to /etc/nginx/nginx.conf (or /etc/nginx/conf/nginx.conf if you're using Arch Linux).

# Generic startup file.
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/*;
}

Now, you'll observe that this is a bit different from most nginx.conf files. I opted to follow the Ubuntu/Debian method of declaring enabled sites for maximum flexibility - using 'sites-available' to store a config and then symlink to the config file from 'sites-enabled'. It takes a little extra effort to set up but is well worth that effort for managing multiple websites.

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;
}

If you look around the Internet, you can find various WordPress configs for nginx. Most of them drop stuff into the 'server' block, but I figure some people might want to reuse the same logic over and over. As long as the blog is in the root of the site, this is no problem. I created a 'global' subdirectory to add extra rules for general purpose use and performing quick WordPress setups (either /etc/nginx/conf/global/ or /etc/nginx/global/ depending on how your nginx install is set up).

Global restrictions file

# Global restrictions configuration file.
# Designed to be included in any server {} block.</p>
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

For single blog installations here is the 'global/wordpress.conf' file:

# 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

For multisite subdirectory installations, here is the 'global/wordpress.conf' file:

# 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;
}

This configuration may also work for subdomain installations without modification. This configuration may also work for a single blog installation (non-network/multisite).

WP Super Cache Rules

# 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;
}

W3 Total Cache Rules

# BEGIN W3TC Browser Cache
gzip on;
gzip_types text/css application/x-javascript text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
location ~ \.(css|js)$ {
    expires 31536000s;
    add_header Pragma "public";
    add_header Cache-Control "max-age=31536000, public, must-revalidate, proxy-revalidate";
    add_header X-Powered-By "W3 Total Cache/0.9.2.3";
}
location ~ \.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml)$ {
    expires 180s;
    add_header Pragma "public";
    add_header Cache-Control "max-age=180, public, must-revalidate, proxy-revalidate";
    add_header X-Powered-By "W3 Total Cache/0.9.2.3";
}
location ~ \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
    expires 31536000s;
    add_header Pragma "public";
    add_header Cache-Control "max-age=31536000, public, must-revalidate, proxy-revalidate";
    add_header X-Powered-By "W3 Total Cache/0.9.2.3";
}
# END W3TC Browser Cache
# BEGIN W3TC Skip 404 error handling by WordPress for static files
if (-f $request_filename) {
    break;
}
if (-d $request_filename) {
    break;
}
if ($request_uri ~ "(robots\.txt|sitemap(_index|[0-9]+)?\.xml(\.gz)?)") {
    break;
}
if ($request_uri ~* \.(css|js|html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$) {
    return 404;
}
# END W3TC Skip 404 error handling by WordPress for static files

If you don't have the static gzip module compiled in, be sure to comment out the correct line.

Experimental modifications:

Some setups using these WP Super Cache rules may have issues with trailing slashes not redirecting to/displaying the correct post in the blog when a trailing slash does not exist. Typically a problem for permalink structures of /%post_id%/. For such setups, modify the above configuration file as follows:

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;
}

These modifications might work better overall as they potentially reduce the number of hits to the WP engine.

If you are using the latest development version of WP Super Cache (current 'stable' at the time of this writing is 0.9.9.9), it looks like donncha has changed the way the directory structure is laid out to differentiate between HTTP and HTTPS. The ${scheme} variable will eventually become a necessary part of the path. This modification will need to be applied if you are using the latest development version or a new stable release beyond 0.9.9.9 comes out:

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

A little more performance

If you are feeling adventuresome and want to squeak out a little tiny bit more performance, use a custom script like this and run it (and needs to be run after each new blog is created after that).

<?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);
		}
	}
?>

The PHP script generates symbolic links from the names of the blogs to the numeric (ID) representation of each blog. Then, nginx doesn't pass requests for uploaded files to php-fpm. If you don't plan on doing this, comment out the relevant rules to save a few CPU cycles per request.

Also, if you don't have a mobile site WP theme, comment out the relevant WP Super Cache rules for mobile browsers to save a lot of CPU cycles.

Notes

A couple last notes: This whole setup assumes that the root of the site is the blog and that all files that will be referenced reside on the host. If you put the blog in a subdirectory such as /blog, then the rules will unfortunately have to be modified to handle that situation. Perhaps someone can take these rules and make it possible to, for instance, use a:

set $wp_subdir "/blog";

Directive in the main 'server' block and have it automagically apply to the generic WP rules.

Resources

Reference

External Links

最新英語版: WordPress Codex » Nginx最新版との差分