使用Nginx+Redis为WordPress访问加速

更新:在宝塔面板直接安装php扩展 redis,然后在wordpress安装Redis Object Cache,启用缓存即可。

在ssh执行以下命令,然后刷新网站进行验证。

redis-cli monitor

以下为旧资料:

环境:宝塔面板,Nginx,PHP,Wordpress,Redis

插件:Nginx-Help, Redis Object Cache , WPRedis

一、首先,需要给Nginx配置以下4个模块

srcache-nginx-module
redis2-nginx-module
HttpRedisModule
set-misc-nginx-module

宝塔面板,后台切换Nginx可以选择 nginx openresty ,自带以上模块

下面用来确认已经配置4个模块,会返回已经安装

nginx -V 2>&1 | grep 'srcache-nginx-module\|redis2-nginx-module\|redis-nginx-module\|set-misc-nginx-module' -o

二、在宝塔面板PHP配置中添加Redis扩展

三、在站点的Nginx配置文件的最上面,在server { }外面添加下面的代码

upstream redis {
            server 127.0.0.1:6379;
            keepalive 512;
    }

server { }里添加下面的代码

  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 /redis-fetch {
        internal  ;
        set  $redis_key $args;
        redis_pass  redis;
    }
 
    location /redis-store {
        internal  ;
        set_unescape_uri $key $arg_key ;
        redis2_query set $key $echo_request_body;
        redis2_query expire $key 14400; 
        redis2_pass  redis;
    } 
 
 
     location ~ [^/]\.php(/|$){
        set $key "nginx-cache:$scheme$request_method$host$request_uri";
        try_files $uri =404;
    
 
        srcache_fetch_skip $skip_cache;
        srcache_store_skip $skip_cache;
 
        srcache_response_cache_control off;
 
        set_escape_uri $escaped_key $key;
 
        srcache_fetch GET /redis-fetch $key;
        srcache_store PUT /redis-store key=$escaped_key;
 
        more_set_headers 'X-Cache $srcache_fetch_status';
        more_set_headers 'X-Store $srcache_store_status';
        add_header X-Cache "$srcache_fetch_status From $host";
        add_header X-Frame-Options SAMEORIGIN; # 只允许本站用 frame 来嵌套
        add_header X-Content-Type-Options nosniff; # 禁止嗅探文件类型
        add_header X-XSS-Protection "1; mode=block"; # XSS 保护   
    
        fastcgi_pass unix:/tmp/php-cgi-72.sock;     #这里php版本不一样请注意修改
        fastcgi_index index.php;
        include fastcgi.conf;
    }

保存,重启Nginx

四、在Wordpress插件管理中搜索安装 Nginx-Help, Redis Object Cache , WP Redis

激活Nginx-Help,进入设置,启用Enable purge ,在Caching Method选择Redis cache,在Redis Settings中修改Predix值,这里不要和其它站点冲突, 在Purging Options 中选择所需的缓存清理选项。

保存即可。

安装Redis Object Cache用于缓存刷新,好像也可以使用WP Redis

就这样,结束 。

参考文章: 大鸟博客 https://www.daniao.org/5403.html