前言

FastCGI缓存是一个为动态请求而构建的缓存系统,这个缓存系统最棒的地方在于它不依赖任何外部的PHP-MySQL应用程序或插件来快速提供你的内容。

您甚至不需要依赖代理缓存解决方案(如Varnish),因为FastCGI缓存由Nginx内核托管并提供服务,而无需与其他应用或系统守护进程进行任何外部交互。

今天尝试在博客添加该功能。之前利用Nginx fastcgi_cache缓存对WordPress博客进行加速
写过类似,不过配置文件有些变化,而且打算放弃插件支持,直接在配置文件添加相关规则触发条件。

安装ngx_cache_purge

nginx -V 2>&1 | grep -o ngx_cache_purge #没有任何反馈就是没有安装

cd /root/oneinstack/src
wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar xzf ngx_cache_purge-2.3.tar.gz
tar xzf nginx-1.14.0.tar.gz
cd nginx-1.14.0
nginx -V #查看nginx编译参数,最后加上--add-module=../ngx_cache_purge-2.3
make clean
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_v2_module --with-http_ssl_module --with-ipv6 --with-http_gzip_static_module --with-http_realip_module --with-http_flv_module --with-openssl=../openssl-1.0.2h --with-pcre=../pcre-8.39 --with-pcre-jit --with-ld-opt='-ljemalloc' --add-module=../ngx_cache_purge-2.3
make  #编译
mv /usr/local/nginx/sbin/nginx{,_`date +%F`}  #备份nginx
cp objs/nginx /usr/local/nginx/sbin
nginx -V 2>&1 | grep -o ngx_cache_purge # 显示ngx_cache_purge表示已经安装成功

这里不做再多描述。

配置文件

之前使用的是Nginx Helper插件配合清理缓存,今天尝试抛弃该插件:

在你的域名配置文件头部添加:

fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

server {
    listen   80;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    server_name example.com;

    set $skip_cache 0;
    # post访问不缓存
    if ($request_method = POST) {
        set $skip_cache 1;
    }

    # 动态查询不缓存
    if ($query_string != "") {
        set $skip_cache 1;
    }

    # 后台等特定页面不缓存
    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
        set $skip_cache 1;
    }

    # 对登录用户、评论过的用户不展示缓存
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
        set $skip_cache 1;
    }

    location ~ \.php$ {
        try_files $uri =404;

        include /etc/nginx/fastcgi_params;
.
        fastcgi_read_timeout 360s;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        # Use the upstream for php5-fpm that we defined in nginx.conf
        fastcgi_pass php;

        fastcgi_index index.php;
        # 新增规则
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid  60m;
        add_header X-FastCGI-Cache "$upstream_cache_status From $host";
    }
}

故我的完整的配置如下:

fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

server {
  listen 80;
  listen 443 ssl http2;
  ssl_certificate /usr/local/nginx/conf/ssl/iiong.com.crt;
  ssl_certificate_key /usr/local/nginx/conf/ssl/iiong.com.key;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
  ssl_prefer_server_ciphers on;
  ssl_session_timeout 10m;
  ssl_session_cache builtin:1000 shared:SSL:10m;
  ssl_buffer_size 1400;
  add_header Strict-Transport-Security max-age=15768000;
  ssl_stapling on;
  ssl_stapling_verify on;
  server_name iiong.com www.iiong.com;
  access_log /data/wwwlogs/iiong.com_nginx.log combined;
  index index.html index.htm index.php;
  root /data/wwwroot/iiong.com;
  if ($ssl_protocol = "") { return 301 https://$host$request_uri; }
  if ($host != iiong.com) {  return 301 $scheme://iiong.com$request_uri;  }
  include /usr/local/nginx/conf/rewrite/wordpress.conf;
  include /usr/local/nginx/conf/rewrite/pagespeed.conf;
  rewrite ^/sitemap-xml$ /sitemap.php last;

  set $skip_cache 0;
  # post访问不缓存
  if ($request_method = POST) {
    set $skip_cache 1;
  }

  # 动态查询不缓存
  if ($query_string != "") {
    set $skip_cache 1;
  }

   # 后台等特定页面不缓存
  if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
    set $skip_cache 1;
  }

  # 对登录用户、评论过的用户不展示缓存
  if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
    set $skip_cache 1;
  }

  location ~ .*\.(wma|wmv|asf|mp3|mmf|zip|rar|jpg|gif|png|swf|flv|mp4)$ {
    valid_referers none blocked *.iiong.com iiong.com www.iiong.com;
    if ($invalid_referer) {
        rewrite ^/ http://www.linuxeye.com/403.html;
        return 403;
    }
  }
  location ~ [^/]\.php(/|$) {
    try_files $uri =404;
    fastcgi_pass unix:/dev/shm/php-cgi.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    #新增的缓存规则
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 60m;
    add_header X-FastCGI-Cache "$upstream_cache_status From $host";
  }

  location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
    expires 30d;
    access_log off;
  }
  location ~ .*\.(js|css)?$ {
    expires 7d;
    access_log off;
  }
  location ~ /\.ht {
    deny all;
  }
}

重启服务器service nginx restart

然后在访客模式(退出登录)查看网页的响应头是否有X-FastCGI-Cache字段,如果有则成功了。
QQ截图20180520112846.png

WP优化

将下面代码放在你想放的地方,不过建议像插件一样集成,新建php文件存放在wp-content/plugins文件夹即可:

<?php
/**
 * Plugin Name: NGINX FastCGI缓存清理
 * Version: 1.0
 * Description: 刷新NGINX FastCGI缓存
 * Author: 淮城一只猫
 * Author URI: https://iiong.com
 * Plugin URI: https://iiong.com
 */

if ( ! defined( 'NGINX_CACHE_PATH' ) ) {
    define( 'NGINX_CACHE_PATH', '/var/run/nginx-cache' );
}

final class NGINX_FastCGI_cache_purge {

    public static $instance = null;

    private function __construct() {
        add_action( 'edit_post', [ $this, 'purge_cache' ] );
    }


    /**
     * Creates or returns an instance of this class.
     *
     * @return A single instance of this class.
     */
    public static function init() {
        if ( self::$instance === null ) {
            self::$instance = new self;
        }

        return self::$instance;
    }


    /**
     * Purge a page from the NGINX FastCGI cache.
     *
     * @param int $post_id WP_Post ID.
     */
    public function purge_cache( $post_id ) {
        if ( 'publish' !== get_post_status( $post_id ) ) {
            return;
        }

        $public_post_types = get_post_types([ 'public' => true ]);
        $post_type = get_post_type( $post_id );
        if ( ! in_array( $post_type, $public_post_types ) ) {
            return;
        }

        $url = get_permalink( $post_id );
        if ( ! $url ) {
            return;
        }

        $path = $this->get_cache_path( $url );
        if ( $path ) {
            $this->flush_cache( $path );
        }
    }


    /**
     * Get the path to the cached file from the URL.
     *
     * @param string $url URL to parse.
     *
     * @return string path to the cached page.
     */
    protected function get_cache_path( $url ) {
        if ( ! $url ) {
            return false;
        }

        $url = parse_url( $url );
        $hash = md5( $url['scheme'] . 'GET' . $url['host'] . $url['path'] );
        $path = trailingslashit( NGINX_CACHE_PATH );

        return $path . substr( $hash, -1 ) . '/' . substr( $hash, -3, 2 ) . '/' . $hash;
    }


    /**
     * Flush the cache from the path to the cached file.
     * 
     * @param string $path Path to the cached file to flush.
     * 
     * @return bool True on success or false.
     */
    protected function flush_cache( $path ) {
        if ( file_exists( $path ) ) {
            return unlink( $path );
        }

        return false;
    }

}

NGINX_FastCGI_cache_purge::init();

然后启用即可,该插件作用就是你更新文章刷新下缓存即可。

参考

https://www.ehowstuff.com/setup-wordpress-nginx-with-fastcgi-caching-in-centos-7/
https://medium.com/@Alibaba_Cloud/wordpress-caching-solutions-part-2-configuring-nginx-fastcgi-static-page-caching-and-final-load-3d101dfea5ea
https://gist.github.com/richardsweeney/736465dddce8398357a9


淮城一只猫

永远年轻,永远热泪盈眶

发表评论

电子邮件地址不会被公开。 必填项已用*标注

我不是机器人*

EA PLAYER &

历史记录 [ 注意:部分数据仅限于当前浏览器 ]清空

      00:00/00:00