Nginx安装fastcgi_cache缓存加速

203天前 · 网站 · 205次阅读

Nginx安装ngx_cache_purge模块

默认已经下载并且解压了军哥的lnmp 且压缩目录为lnmp,我们首先进入lnmp的src目录
请先启用Nginx缓存插件后在配置vhost的虚拟主机配置文件,否则会出现奇奇怪怪的问题

cd /root/lnmp/src

然后下载cache插件

wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz

下载完成解压此插件

tar xzf ngx_cache_purge-2.3.tar.gz

回到lnmp目录,编辑lnmp.conf

vim lnmp.conf

修改Nginx_Modules_Options设置

Nginx_Modules_Options='--add-module=/root/lnmp/src/ngx_cache_purge-2.3'

退出保存,按照军哥的教程正常安装LNMP环境就行!

配置网站的conf文件

lnmp的默认虚拟主机文件在/usr/local/nginx/conf/vhost/这个目录
下面的内容放在server{}这个字段上面

fastcgi_cache_path /tmp/nginx levels=1:2 keys_zone=TYPECHO:250m inactive=1d max_size=500m;
fastcgi_temp_path /tmp/temp;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
#忽略一切nocache申明,避免不缓存伪静态等
fastcgi_ignore_headers Cache-Control Expires;

/tmp/nginx路径以及/tmp/temp路径需要自己手动创建或者自定义路径
如果开启了证书需要放在server{listen 443}这个块中,下面的配置需要放在include rewrite/typecho.conf;这行上面

set $cache 0;
#post访问不缓存
if ($request_method = POST) {
            set $cache 1;
        }
#动态查询不缓存
if ($query_string != "") {
            set $cache 1;
        }
if ($request_uri ~* "/purgeall/|/action/|/admin/|/admin/*.php|/feed/|/sitemap/|index.php|sitemap(_index)?.xml") {
  set $cache 1;
        }
if ($http_cookie ~* "PHPSESSID|typecho_authCode|typecho_uid|typecho_remember_mail|typecho_remember_author|typecho_remember_url") {
    set $cache 1;
    }

下面的配置需要放在error_page 404 /404.html;这行下面

location ~ .*\.php(\/.*)*$ {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
set $path_info "";
set $real_script_name $fastcgi_script_name;
if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
  set $real_script_name $1;
  set $path_info $2;
}
fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
fastcgi_param SCRIPT_NAME $real_script_name;
#fastcgi_param PATH_INFO $path_info;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
#新增的缓存规则
fastcgi_cache_bypass $cache;
fastcgi_no_cache $cache;
add_header X-Cache "$upstream_cache_status From $host";
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 TYPECHO;
fastcgi_cache_valid 200 301 302 1d;
}

请注意这个语句fastcgi_pass unix:/dev/shm/php-cgi.sock;
后面的是php cgi的路径,请在/usr/local/php/etc/php-fpm.conf中修改listen为相同的路径

listen = /dev/shm/php-cgi.sock

到此专门配置typecho缓存规则完成,nginx-cache也已经启动

Typecho自动清除Nginx缓存插件

下载下方的这个插件,按照步骤修改相应的路径,然后在插件后台启用即可
NginxHelper

如果需要看到效果,浏览器按F12打开开发者工具,选择网络,然后找到页面,鼠标单机查看响应头,有如下显示表示Nginx缓存启用正常

nginx-cache: BYPASS

BYPASS表示未缓,MISS表示未命中HIT表示缓存命中

Nginx

最后修改于200天前