php fastcgi cache config rules

原创
2018/03/07 14:17
阅读数 123

对于一些静态内容,如果想简单的实现程序一级的缓存,除了opcache,还可以在fastcgi一层实现,配置如下。 如果还不清楚哪个url可以缓存,建议先设$skip_cache为1,然后对要开缓存的单独再配置开启,这样更保险一些。速度可以几十倍的提升!因为直接绕开PHP的解析和执行,效果跟反向代理差不多。配置好后注意仔细测试添加的规则是否按设置正常运行了,避免动态程序被缓存导致的异常。

# ---------------------------------------------------------------------
# NGINX - FastCGI CACHE configuration
# ---------------------------------------------------------------------
# Created by Ryadel on 2017.12.09
# www.ryadel.com
# ---------------------------------------------------------------------
 
user www;
 
worker_processes 2;
working_directory /var/www;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
 
include /usr/share/nginx/modules/*.conf;
 
events {
    worker_connections 1024;
}
 
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
 
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
 
    # ---------------------------------------------------------------------
    # FASTCGI GLOBAL CONFIGURATION - START
    # ---------------------------------------------------------------------
    # below lines must be outside server blocks to enable FastCGI cache for Nginx
    # path can be anywhere, app name must be consistent, total size small enough to avoid RAM depletion
  
    fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=WORDPRESS:256m inactive=30m;
    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;
 
    # ---------------------------------------------------------------------
    # FASTCGI GLOBAL CONFIGURATION - END
    # ---------------------------------------------------------------------
  
    # Custom header that will tell us if the response page has been served from cache (HIT) or from the upstream host (BYPASS or MISS).
    add_header X-FastCGI-Cache $upstream_cache_status;
 
    server {
        listen       80;
        server_name  www.yourwebsite.com default_server;
 
        root         <path_to_your_website_files>;
        index        index.php;
        autoindex off;
 
        set $skip_cache 0;
 
        # ---------------------------------------------------------------------
        # CACHE SKIP RULES - START
        # ---------------------------------------------------------------------
 
        # Do not cache POST requests - they should always go to PHP
        if ($request_method = POST) {
            set $skip_cache 1;
        }
 
        # Do not cache URLs with a query string - they should always go to PHP
        if ($query_string != "") {
            set $skip_cache 1;
        }
 
    # WooCommerce-specific cache skip rules
    if ($request_uri ~* "/store.*|/cart.*|/my-account.*|/checkout.*|/addons.*") {
      set $skip_cache 1;
        set $skip_cache_reason WP_WooCommerce;
    }
 
    if ($cookie_woocommerce_items_in_cart) { 
        set $skip_cache 1; 
        set $skip_cache_reason WP_WooCommerce;
      }
 
    if ($request_uri ~* ("/cart.*")) { 
            set $skip_cache 1; 
        }
 
        # Don't cache URIs containing the following segments (admin panel, sitemaps, feeds, etc.)
    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 $skip_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 $skip_cache 1;
        }
 
        # ---------------------------------------------------------------------
        # CACHE SKIP RULES - END
        # ---------------------------------------------------------------------
 
        location / {
            try_files $uri $uri/ /index.php?$args;
        }
 
        location ~ \.php$ {
 
            try_files $uri =404; # comment out this line if php-fpm is hosted on a remote machine
            include /etc/nginx/fastcgi.conf;
 
            limit_req zone=limit_req_php burst=20 nodelay;
 
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
            fastcgi_cache WORDPRESS;
            fastcgi_cache_valid 200 60m;
            fastcgi_cache_bypass $skip_cache;
            fastcgi_no_cache $skip_cache;
            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            if (!-f $document_root$fastcgi_script_name) {
                return 404;
            }
        }
    }
}

注意:如果使用了rewrite,对路径进行了修改的,匹配路径时要使用修改之后的路径,否则$skip_cache可能不会生效。安全的做法是rewrite前、后的路径都配置一下。

nginx fastcgi cache module 各指令的详细解释

http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部