Nginx配置多站点下如何设置Fastcgi_cache缓存加速?

这是本人备份,不懂可以忽略

Nginx配置多站点下如何设置Fastcgi_cache缓存加速?

Nginx配置多站点下如何设置Fastcgi_cache缓存加速?

记录分享了 Nginx 的 Fastcgi 缓存之后,在我给第二个站配置缓存的时候就出现了问题,马上就网上找到教程修复完成在多站点下配置 Nginx Fastcgi。经过参考张戈的教程,最终试出了多站点下的 Fastcgi 缓存配置,下面简单记录分享下。

一、部署 http 模块

下面分别讲下单站点和多站点的配置对比:

①、单个站点

单个站点上篇文章已经分享过了,在 http 模块内加入如下配置即可:

fastcgi_cache_path /tmp/wpcache levels=1:2 keys_zone=WORDPRESS:150m inactive=31d max_size=10G;
fastcgi_temp_path /tmp/wpcache/temp;
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 缓存时,以上配置就不行了,会报错、也有可能会多个网站之间链接错乱。经过测试,修改如下即可:

②、多个站点

 

#站点 1 缓存配置
fastcgi_cache_path /tmp/xkj_cache levels=1:2 keys_zone=xkj:200m inactive=1d max_size=1G;
#站点 2 缓存配置
#如果要开启更多站点缓存,请继续增加,注意每个站点的 缓存路径 和 keys_zone 要自定义区分一下
#Ps:代码中的参数都只是范例,实际使用请根据服务器配置自行修改
fastcgi_cache_path /tmp/93665_cache levels=1:2 keys_zone=93665:200m inactive=1d max_size=1G;
#其他配置可以不变
fastcgi_temp_path /tmp/temp_cache;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;

 

二、部署 server 模块
配置好了 http 模块之后,server 模块就很简单了!只要在不同的站点的 php 模块下插入不同的 fastcgi 缓存配置即可,其实就是 key_zone 的区别而已。

这个位置#SSL-END
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.xml|/sitemap_*.xml|sitemap(_index)?.xml|sitemap-*.xml|/pay|/notify|/return|/download") {
set $skip_cache 1;
}
#对登录用户、评论过的用户不展示缓存
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9] |wp-postpass|wordpress_no_cache|wordpress_logged_in|b2_token") {
set $skip_cache 1;
}
#这里请参考你网站之前的配置,特别是sock的路径,弄错了就502了!如果你的网站使用PHP7.4,就写-74.sock
location ~ [^/].php(/|$)
{
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi-74.sock;
fastcgi_index index.php;
include fastcgi.conf;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
#新增的缓存规则
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
add_header X-Cache "$upstream_cache_status From $host";
fastcgi_cache 93665;
add_header Cache-Control max-age=0;
add_header Nginx-Cache "$upstream_cache_status";
add_header Last-Modified $date_gmt;
add_header X-Frame-Options SAMEORIGIN; # 只允许本站用 frame 来嵌套
add_header X-Content-Type-Options nosniff; # 禁止嗅探文件类型
add_header X-XSS-Protection "1; mode=block"; # XSS 保护
etag on;
fastcgi_cache_valid 200 301 302 1d;
}
#缓存清理配置
location ~ /purge(/.*) {
allow 127.0.0.1;
allow "xxxxx"; # 引号要保留
deny all;
fastcgi_cache_purge 93665 "$scheme$request_method$host$1";

 

 

来自



微信扫描下方的二维码阅读本文