NginxのCacheがとても速いのは前回の記事でよく分かりましたが、Webサーバーと
Proxyサーバーをそれぞれ用意するのはリソースの無駄に思えます。
と言うわけで、Nginxのもう一つのCache機能であるFastCGI Cacheに設定を変更しました。
Proxy CacheはNginxがバックエンドのWebサーバーに処理を転送し返ってきたコンテンツを
キャッシュして、Nginx自身はキャッシュを送信することでパフォーマンスを上げる仕組みです。
今回導入したFastCGI CacheはFastCGIのレスポンスをキャッシュする機能です。
これを利用すると、Proxy Cacheを利用したのと同じ効果をProxyサーバーなしに実現できますので、
無駄な通信と処理がなくなりシンプルな構成となります。
設定も通常のFastCGIを使う設定にCache設定を追加するだけなので、シンプルで簡単です。
Cache制御の設定もProxyの時と同じ考え方で設定できます。
2013/01/13 設定を修正しました。
HEADアクセスで空のキャッシュが出来てしまう現象の対策
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
directio 8m;
keepalive_timeout 30;
# CacheのHIT/MISSなどの情報をログに出力
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $upstream_cache_status';
gzip on;
gzip_http_version 1.1;
gzip_types text/plain
text/xml
text/css
application/xml
application/xhtml+xml
application/rss+xml
application/atom_xml
application/javascript
application/x-javascript ;
gzip_disable "MSIE [1-6]¥." "Mozilla/4";
gzip_comp_level 1;
gzip_proxied any;
gzip_vary on;
gzip_buffers 4 8k;
gzip_min_length 1000;
fastcgi_cache_path /var/tmp/nginx/fcache levels=1:2
keys_zone=fcache:8m max_size=100m inactive=7d;
server {
listen 80;
server_name mmio.net;
access_log /var/log/nginx-blog.log main;
# 静的ファイルの配信
location / {
root /home/www/blog/ ;
index index.html index.htm index.php;
location ~* \.(jpg|jpeg|gif|png|css|js|ico)$ {
expires 14d;
}
# WordPressのパーマリンク対策
try_files $uri $uri/ /index.php;
}
location = /favicon.ico { log_not_found off; }
location = /robots.txt { log_not_found off; }
location ~ /\.ht { deny all; }
# モバイルデバイスはキャッシュを使わない
if ($http_user_agent ~* '(DoCoMo|UP\.Browser|SoftBank|WILLCOM|
emobile|iPhone|iPod|Android.*Mobile)') {
set $do_not_cache 1;
}
# WordPressにログイン中はキャッシュを使わない
if ($http_cookie ~* "wordpress_logged_in_[^=]*=([^%]+)%7C") {
set $do_not_cache 1;
}
# HEADアクセスはキャッシュを使わない
if ($request_method = "HEAD") {
set $do_not_cache 1;
}
# PHP処理をFastCGIに転送
location ~ \.php$ {
fastcgi_pass unix:/tmp/php.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/www/blog/$fastcgi_script_name;
fastcgi_cache fcache;
fastcgi_no_cache $do_not_cache;
fastcgi_cache_bypass $do_not_cache;
fastcgi_cache_key $scheme://$host$request_uri;
fastcgi_cache_valid 200 7d;
fastcgi_cache_valid 301 7d;
fastcgi_cache_valid any 10m;
include fastcgi_params;
}
# Cache破棄のためのURL
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 49.212.135.193;
deny all;
fastcgi_cache_purge fcache $scheme://$host$1;
}
}
}
キャッシュ保持期間が7日とやや長めですが、記事の更新時に自動的にキャッシュを破棄する
仕組みを導入していますので、更新がいつまでも反映されないという事態は発生しないはず。
ngx_cache_purgeモジュールを組み込んでいない環境であれば、保持期間は10分程度にしておくのが
無難だと思います。
とりあえずは、不具合などが起きない限りこの設定で運用してみたいと思います。
ピンバック: FastCGI Cacheの設定を更新しました « 404 – Not Found
I truly wanted to post a small remark in order to