静的WordPress向けNginxのfastcgi_cache設定

nginx_wordpressWordPressで開発した静的ウェブサイトを公開するためにnginxの設定を見直したときの覚書。

環境: CentOS 6.7, nginx 1.8.0, PHP 5.6.15

fastcgi_cacheはPHP-FPMなどのバックエンドの結果をキャッシュする機能。

Nginxの設定ファイルの記述はWordPressの公式サイトを参考にした。

 

設定ファイルをGistにアップしたのでこっちを見ながらの方が分かりやすいかも。

 

目次

  1. FastCGIキャッシュ機能を有効に
  2. Nginxの設定ファイルを準備(キャッシュなし)
  3. キャッシュ機能が有効な設定ファイル
  4. Gzipの設定ファイル

 


1.FastCGIキャッシュ機能を有効に

Nginx全体の設定なのでhttpディレクティブに記述する必要がある。
# cd /etc/nginx/
# less nginx.conf

http {
    # FastCGI Cache
    fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=WORDPRESS:100m inactive=1d;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
    fastcgi_cache_use_stale error timeout invalid_header http_500;
}

ゾーン名: WORDPRESS
共有メモリ使用サイズ: 100M
保持期間: 1日間

 


2.Nginxの設定ファイルを準備(キャッシュなし)

各サイトごとの設定
# cd conf.d/

共通の設定ファイルを作って、各サイトでincludeさせる。

まずはアクセス制限用設定ファイルを作成
# mkdir global
# vi global/wordpress_restrictions.conf

#
# Global Restrictions for WordPress site
# 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).
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~ /\. {
    deny all;
}

# Deny access to any files with a .php extension in the uploads directory
# Works in sub-directory installs and also in multisite network
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~* /(?:uploads|files)/.*\.php$ {
    deny all;
}

 

シングルサイト用WordPress設定ファイル。まずはfastcgi_cacheを使わない設定。
# vi global/wordpress_dev.conf

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

index   index.php;
charset utf-8;

# 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 ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
    access_log off; log_not_found off; expires max;
}

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    if (!-f $document_root$fastcgi_script_name) {
        return 404;
    }
    # This is a robust solution for path info security issue and works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_index index.php;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_intercept_errors on;

    client_max_body_size 5M;
}

 

これらのファイルをincludeしてサイトが表示できるか確認。
# vi 01_hoge.conf

server {
    listen       80;
    server_name  dev.hoge.jp;

    root    /home/httpd/project/web/wordpress;

    # WordPress Setting
    include conf.d/global/wordpress_restrictions.conf;
    include conf.d/global/wordpress_dev.conf;
}

設定ファイルを再読み込みしてブラウザで確認
# /etc/rc.d/init.d/nginx configtest
# /etc/rc.d/init.d/nginx reload

 


3.キャッシュ機能が有効な設定ファイル

今度はfastcgi_cacheを有効にした設定。

前のをコピーして使う
# cp global/wordpress_dev.conf global/wordpress_live.conf

キャッシュに関わる設定を追記
# less global/wordpress_live.conf

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

index   index.php;
charset utf-8;


#
# fastcgi_cache start
# https://codex.wordpress.org/Nginx#Nginx_fastcgi_cache
set $no_cache 0;

# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
    set $no_cache 1;
}
if ($query_string != "") {
    set $no_cache 1;
}

# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
    set $no_cache 1;
}

# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
    set $no_cache 1;
}


# 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 ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
    access_log off; log_not_found off; expires max;
}

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    if (!-f $document_root$fastcgi_script_name) {
        return 404;
    }
    # This is a robust solution for path info security issue and works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_index index.php;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_intercept_errors on;

    client_max_body_size 5M;

    # Enable FastCGI cache
    fastcgi_cache_bypass $no_cache;
    fastcgi_no_cache $no_cache;

    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 200 60m;
}

 

これをincludeしてブラウザで確認
# less 01_hoge.conf

server {
    listen       80;
    server_name  dev.hoge.jp;

    root    /home/httpd/project/web/wordpress;

    # WordPress Setting
    include conf.d/global/wordpress_restrictions.conf;
    #include conf.d/global/wordpress_dev.conf;
    include conf.d/global/wordpress_live.conf;
}

 

nginx再読み込み
# /etc/rc.d/init.d/nginx configtest
# /etc/rc.d/init.d/nginx reload

2回目以降の読み込みが速くなっているはず。

 

キャッシュをクリアする仕組みを用意しておく
# vi global/fastcgi_cache_purge.conf

#
# FastCGI Cache Purge
#
location ~ /purge(/.*) {
    # Uncomment the following two lines to allow purge only from the webserver
    #allow 127.0.0.1;
    #deny all;

    fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
}

。。。と思ったけど、yumでインストールするとfastcgi_cache_purgeモジュールが有効になっていないらしい。

コマンドで削除する
# rm -rf /var/cache/nginx/fastcgi/*

 


4.Gzipの設定ファイル

おまけでgzip用の設定も。
# vi global/gzip.conf

gzip         on;
gzip_vary    on;
gzip_proxied any;
gzip_types   text/plain
             text/xml
             text/css
             application/xml
             application/xhtml+xml
             application/rss+xml
             application/atom_xml
             application/javascript
             application/x-javascript
             application/x-httpd-php;
gzip_disable "MSIE [1-6]\.";
gzip_buffers 16 8k;

これをincludeしてブラウザで確認
# less 01_hoge.conf

server {
    listen       80;
    server_name  dev.hoge.jp;

    root    /home/httpd/project/web/wordpress;

    # Gzip
    include conf.d/global/gzip.conf;

    # WordPress Setting
    include conf.d/global/wordpress_restrictions.conf;
    #include conf.d/global/wordpress_dev.conf;
    include conf.d/global/wordpress_live.conf;
}

nginx再読み込み
# /etc/rc.d/init.d/nginx configtest
# /etc/rc.d/init.d/nginx reload

 

関係ないけどRedisを利用したオブジェクトキャッシュを有効にしたら、パフォーマンスが悪くなった。

 

< Related Posts >