「nginx + WordPress + multisite」で、アップロードしたファイルをちゃんと表示できるようになった
2012年11月13日
「nginx + WordPress + multisite」で、アップロードしたファイルをちゃんと表示できるようになったので、簡単に記録しておきます。
ぶち当たった問題
- 画像をアップロードして記事に埋め込んだが、画像が表示されない(404エラー)
原因
- nginxの設定
解決方法
- WordPressで「nginx-helper」というプラグインを入れて、適切に設定する
- nginxの設定ファイルを適切に設定する。
参考になったページ
細かいこと
参考にしたページの設定は、「nginx-helper」というプラグインを利用するのが前提になっているようなので、忘れずに入れて設定しておきます。
プラグイン設定方法は、以下のとおりです。
- 「nginx-helper」をインストールする。
- 画面左側のメニューから「設定」→「Nginx Helper」とクリックして設定画面を出す。
- 「Enable Nginx Map.」にチェックを入れて「Save」します。
プラグインについては以上です。
ただし、このプラグインの情報にしたがって、nginxの設定を書きなおす必要があります。
必要な情報は以下のとおりです。
- 「save」した後、「Nginx Map」という設定が出てくるので、その中の「Nginx Map path to include in nginx settings」の右側の文字列をコピーして貼り付けます。
default -999;
include (ここに貼り付け);
}
(中略)
#WPMU Files
location ~ ^/files/(.*)$ {
try_files /wp-content/blogs.dir/$blogid/$uri /wp-includes/ms-files.php?file=$1;
access_log off; log_not_found off; expires max;
}
```
マルチサイトにした場合、サイト(ブログ)をごとに$blogidが割り振られますが、サイトのホスト名とIDを紐付けておくことで、nginxで画像を処理できるようになります。
この設定は、PHPの起動回数を減らすことにつながるので、サーバーの負荷を減らしたり、高速化を目指す場合は必須です。
で、問題は、この「WPMU Files」の設定なのですが、他の静的なファイルの設定は、この設定よりも前には書かないほうがよさそうです。
confファイル
最後に、ヴァーチャルホストの設定ファイルを晒しておきます。
継ぎ接ぎだらけですが、何かのお役に立てば幸いです。
```default map $http_host $blogid {default -999;
include /var/www/soc/wp-content/plugins/nginx-helper/map.conf;
}
server {
listen 80;
server_name .wp.nishimiyahara.net;
access_log /var/log/nginx/wp_soc.access.log;
error_log /var/log/nginx/wp_soc.error.log;
root /var/www/soc;
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 / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
}
#WPMU Files
location ~ ^/files/(.*)$ {
try_files /wp-content/blogs.dir/$blogid/$uri /wp-includes/ms-files.php?file=$1;
access_log off;
log_not_found off;
expires max;
}
#WPMU x-sendfile to avoid php readfile()
location ^~ /blogs.dir {
internal;
alias /var/www/soc/wp-content/blogs.dir;
access_log off;
log_not_found off;
expires max;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
log_not_found off;
expires max;
}
}
```