php fastcgi cache config rules

本文介绍了一种通过Nginx的FastCGI缓存模块来提高网站性能的方法。具体包括如何配置FastCGI缓存路径、缓存键、缓存规则等,并给出了详细的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于一些静态内容,如果想简单的实现程序一级的缓存,除了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

转载于:https://my.oschina.net/swingcoder/blog/1631005

# 注:这是访问方式为 http://IP:PORT/ 的配置 server { listen 80; server_name X.X.X.X; root /var/www/nextcloud; index index.html index.htm index.php; # 下面这行是设置上传文件大小限制,0 不限制大小,100M 限制文件大小不超过 100M client_max_body_size 0; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php(?:$|/) { fastcgi_split_path_info ^(.+\.php)(/.+)$; # 要注意下面这行的接口的版本,版本要与 php 的版本一样,可以去指定的地址查看一下 fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } location ~ /\.ht { deny all; } # 解决 nextcloud 中的一个安全检查的 .mjs 问题 location ~* \.mjs$ { types { } default_type application/javascript; } location ^~ /.well-known { # The rules in this block are an adaptation of the rules # in `.htaccess` that concern `/.well-known`. location = /.well-known/carddav { return 301 /remote.php/dav/; } location = /.well-known/caldav { return 301 /remote.php/dav/; } location /.well-known/acme-challenge { try_files $uri $uri/ =404; } location /.well-known/pki-validation { try_files $uri $uri/ =404; } # Let Nextcloud's API for `/.well-known` URIs handle all other # requests by passing them to the front-end controller. return 301 /index.php$request_uri; } # Optional: set long EXPIRES header on static assets location ~* \.(?:jpg|jpeg|gif|bmp|ico|png|css|js|swf)$ { expires 30d; access_log off; } }
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值