WordPressのCODEXの英語版に、Nginx利用時の設定ファイルについてのページがあったので、勉強のために翻訳しました。
全体の設定をするファイルから、シングルインストール用/マルチサイト用設定ファイルやキャッシュプラグイン( WP Super Cache か W3 Total Cache )を使うときのためのファイルをインクルードしているのが特徴です。
翻訳は間違っているところもあると思います。また、コードの中のコメントにも訳を付けましたが、下の方のキャッシュプラグイン用のコード部分は力尽きて訳してません。
また、自分ではまだ試していないので、ちゃんと動くかどうかは分からないです。
翻訳元:http://codex.wordpress.org/Nginx

ロゴってこれなの?
以下、訳。
WordPressサイトは、LAMP(Linux + Apache + MySQL + PHP) で動かすことが多いですが、多くの人たちがApacheに代えてNginxを使い始めています。このページは、Nginxを使ってWordPressを動かしたい人たちに役立つことを目的としています。
ngixnを検討する前に、PHP APCや、WordPressのキャッシュプラグインが、単純にNginxに変更するよりも大きなパフォーマンス向上をもたらしてくれるかもしれないことに留意しましょう。
APCやキャッシュプラグインを使っていないのであれば、NginxはあなたのWordPressサイトをsquatします(意味不明。多分マイナス)。また、WordPressはApacheを前提に作られているのでNginxを想定したサポートは充実しつつあるものの限定的です。
これらを考慮に入れた上で導入を決定しましょう。
この記事は、Nginxのインストールや設定については触れません。既にインストールされていて、Nginxの使い方に理解があることを前提としています。
注意:動作テストした環境:
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)
目次(略)
シングルインストール・ネットワークインストールサポート
WordPressをNginxで動かすためには、バックエンドcgiの設定が必要です。fastcgiとphp-fpmの選択肢がありますが。ここでは、php-fpmを使います。その方がベターなのとphp5.3に含まれているためにすぐに使えるからです。
Nginxの設定は、5つのファイルにわかれていて、理解を助けてくれるコメントもたくさん付けられています。作者はベストプラクティス実現のためのベストエフォートをしてくれています。
(ジェネリック)スタートアップファイル
/etc/nginx/nginx.conf (Arch Linux利用の場合は /etc/nginx/conf/nginx.conf )のこと。
# 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().
# bind()できない旨のメッセージをlogに残さない(?)
#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/*;
}
多くのnginx.confファイルとはちょっと違うことが分かるでしょうか。これは、enabled sitesを宣言するUbuntu/Debianメソッドに従っているからです。作った設定を置いておき、sites-enabledからsymlinkすることでsites-availableを利用する柔軟性を最大限引き出しています。ちょっと努力が必要ですが、複数のサイトを管理しようとするならやってみる価値ありです。
サイトごとの設定
# 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;
}
インターネット上にたくさんあるNginxを使ったWordPressのための設定の多くは、設定をserverブロックに分割しています。が、わたしはこれらのロジックを何度も使いまわしたい人がいるのではないかと考えます。ブログがサイトのルートにあるのであれば、それで問題ありません。
わたしは、(多くのサイトに)普遍的な利用とWordPressを迅速にセットアップすることのために、globalというサブディレクトリを作って特別にルールを追加しています。
( /etc/nginx/conf/global/ または、 /etc/nginx/global/ のどちらかです。環境によります。)
グローバルリストリクション設定ファイル
# Global restrictions configuration file.
# グローバルリストリクション設定ファイル
# Designed to be included in any server {} block.</p>
# server{}ブロックからインクルードさせられます。
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).
#.htaccess, .htpasswd, .DS_Store (Mac)などの隠しファイルへのアクセスを制限します。
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
一般的なWordPressルール(シングルインストールのこと?)
global/wordpress.confファイル。シングルインストール向け。
# WordPress single blog rules.
# シングルインストール向けのルール
# Designed to be included in any server {} block.
# server{}ブロックからインクルードさせられます。
# 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.
# */wp-adminへのリクエストがあったら末尾にスラッシュを付ける
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# Directives to send expires headers and turn off 404 error logging.
# expires headersを送り、404エラーをログしないようにするディレクティブ
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.
# phpファイルをphp-fpm/php-fcgiサーバに送る
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.
# ファイルがこのサーバにないときちんと動きません。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.
# php-fpm/php-fcgiを他のサーバに置いている場合はtry_filesをコメントアウト。ハックされないようにお祈りしましょう。
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;
}
マルチサイトルール
マルチサイトで、サブディレクトリ型の場合のルール。global/wordpress.confファイル。
下記の設定は、サブドメイン型でも編集なしで使えます。シングルインストールも大丈夫です。
# WordPress multisite subdirectory rules.
# サブディレクトリ用のルール
# Designed to be included in any server {} block.
# server{}ブロックからインクルードさせられます。
# 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.
# */wp-adminへのリクエストがあったら末尾にスラッシュを付ける
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# Directives to send expires headers and turn off 404 error logging.
# expires headersを送り、404エラーをログしないようにするディレクティブ
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 24h;
log_not_found off;
}
# Pass uploaded files to wp-includes/ms-files.php.
# アップロードファイルを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.
# URIを書き換えて、以降、やり直したり他のルールに進まないようにリライトプロセスを停止します。
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'.
# '.../wp-.*' と '.../*.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.
# phpファイルをphp-fpm/php-fcgiサーバに送る
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.
# ファイルがこのサーバにないときちんと動きません。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.
# php-fpm/php-fcgiを他のサーバに置いている場合はtry_filesをコメントアウト。ハックされないようにお祈りしましょう。
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 ルール
# 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 ルール
# 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
static gzipモジュールをコンパイルしてない場合は、該当箇所をコメントアウトしてください。
実験的設定:
WP Suprer Cacheルールを使ったセットアップで、末尾のスラッシュがない場合に正しい投稿へのリダイレクト、表示がなされない問題があります。/%post_id%/を使ったパーマリンク構造で典型的に起こります。そういう場合、上記の設定を下記のように変更してください。
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;
}
これらの変更はWordPressエンジンへのヒットを減らすはずなので、なんにせよ上手くいくでしょう。
開発バージョンであるWP Super Cache を使っている場合(現在の安定板は、執筆時で 0.9.9.9)。作者がHTTPとHTTPSの識別方法を変更した模様です。${scheme}変数がパスの中で使われる必要があります。この変更は開発版カ、0.9.9.9以降の安定板で必要になります。
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";
}
もうちょっとパフォーマンス向上
冒険心があり、もうあとほんの少しのパフォーマンス向上を望む場合、下記のコードを実行しましょう。(ブログが作られるたびに実行される必要があります。)
<?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);
}
}
?>
このphpスクリプトはブログの名前から各ブログのブログIDへのシンボリックリンクを生成します。すると、Nginxはアップロードされたファイルへのリクエストをphp-fpmへ送らなくなります。これをしたくない場合、該当箇所をコメントアウトして、リクエストごとに発生するCPUサイクルを削減しましょう。
また、モバイルサイトを持っていない場合、WP Super Cache用ルールの関連箇所をコメントアウトして、CPU資源を大幅に削減できます。
注意
以上の設定は、ブログがルート、そして参照される全てのファイルがこのホストに置かれていることを前提にしています。もし、ブログを/blogのようなサブディレクトリに設置している場合、上記の設定は残念ながら変更が必要です。誰かがなんとかしてくれると思いますが、それまでの間、下記を使いましょう。
set $wp_subdir "/blog";
メインのserver{}ブログに設置すれば、全部のルールに適応されます。
リソース
関連:nginx + php-fpm + PHP APC + WordPress multisite (subdirectory) + WP Super Cache
外部リンク:Nginx WordPress wiki page
(外部リンク他にもあったが省略。下記参照)
翻訳元:http://codex.wordpress.org/Nginx
コメント