WordPress使用Nginx提速
发布于 4 年前 作者 kelvv 5142 次浏览 来自 分享

前言

使用WordPress搭建好网站以后,我们需要优化网站的访问速度。要整体提升网站的速度,需要不同的优化策略配合。尽量减少非必要的功能、把网站上的图片放到cdn中、压缩js、压缩css等,那么今天我想给大家介绍方法的是:Nginx缓存

有了nginx缓存,可以让你的网站提速1倍以上,光速博客(gsbk.org)在没有使用nginx缓存前需要1500毫秒才能完全加载首页,使用了nginx缓存以后,加载速度平均在600毫秒以内。

实现

我们按照以下步骤进行操作:

1. 安装Nginx ngx_cache_purge模块

打开服务器命令行工具,检查nginx模块是否已经安装

nginx -V 2>&1 | grep -o ngx_cache_purge

如果出现 ngx_cache_purge ,代表已经安装成功 image.png

2. 打开Nginx配置文件,开启fastcgi_cache缓存配置

记住这里需要修改的是nginx的核心配置文件,而不是网站的配置文件,因为如果给每个网站的nginx配置文件都添加fastcgi_cache缓存的话,可能会冲突。

找到服务器上Nginx的配置文件,然后打开修改,把以下内容添加到http配置内,缓存文件地址:/tmp/wpcache、/tmp/wpcache/temp请自行创建好。

    fastcgi_cache_path /tmp/wpcache levels=1:2
    keys_zone=WORDPRESS:250m inactive=1d max_size=1G;
    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;
    #忽略一切nocache申明,避免不缓存伪静态等
    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

image.png

3. 网站配置fastcgi_cache缓存规则

我们应该给不同的网站创建nginx配置,这样在修改配置的时候就不会互相影响,我们直接修改某个网站的nginx配置,如下:

server
{
    listen 80;
    listen 443 ssl http2;
    server_name gsbk.org www.gsbk.org;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/gsbk.org;
    
    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;
    }
    #这里请参考你网站之前的配置,特别是sock的路径,弄错了就502了!
    location ~ [^/]\.php(/|$)
        {
            try_files $uri =404;
            fastcgi_pass unix:/tmp/php-cgi-72.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 WORDPRESS;
            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 "更换成服务器的真实ip";
        deny all;
        fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
    }
    

    -------------缓存配置到此为止,以下内容无需关注----------------



    #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
    #error_page 404/404.html;
    #HTTP_TO_HTTPS_START
    if ($server_port !~ 443){
        rewrite ^(/.*)$ https://$host$1 permanent;
    }
    #HTTP_TO_HTTPS_END
    ssl_certificate    /www/server/panel/vhost/cert/gsbk.org/fullchain.pem;
    ssl_certificate_key    /www/server/panel/vhost/cert/gsbk.org/privkey.pem;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    error_page 497  https://$host$request_uri;


    #SSL-END
    
    #ERROR-PAGE-START  错误页配置,可以注释、删除或修改
    #error_page 404 /404.html;
    #error_page 502 /502.html;
    #ERROR-PAGE-END
    
    #PHP-INFO-START  PHP引用配置,可以注释或修改
    include enable-php-74.conf;
    #PHP-INFO-END
    
    #REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效
    include /www/server/panel/vhost/rewrite/gsbk.org.conf;
    #REWRITE-END
    
    #禁止访问的文件或目录
    location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
    {
        return 404;
    }
    
    #一键申请SSL证书验证目录相关设置
    location ~ \.well-known{
        allow all;
    }
    
    location / {
     try_files $uri $uri/ /index.php?$args;
    }
     
    # Add trailing slash to */wp-admin requests.
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;
    
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires      30d;
        error_log off;
        access_log /dev/null;
    }
    
    location ~ .*\.(js|css)?$
    {
        expires      12h;
        error_log off;
        access_log /dev/null; 
    }
    access_log  /www/wwwlogs/gsbk.org.log;
    error_log  /www/wwwlogs/gsbk.org.error.log;
}

到这里Nginx缓存已经配置完毕,我们需要重载Nginx配置,然后重启Nginx

nginx -s reload

我们打开网站调试看一下,显示首页已经被nginx缓存命中(HIT)了,加载速度也在600毫秒之内。 image.png image.png

缓存已经生效了,但是当我们更新官网内容的时候,客户刷新页面是拿不到最新的内容的,因为页面读取的是缓存的数据,我们怎么解决这个问题呢?

4. 安装Nginx Helper插件

WordPress有一款插件Nginx Helper,它可以监控Workpress的数据变化,例如文章新增,文章更新,评论新增,评论更新等,然后自动进行缓存的清理,这样当我们创建一篇新文章的时候,插件会识别得到,并且清理首页缓存,客户再次刷新的时候就没有缓存可读,然后走的是数据库查询,首页再次被缓存下来。

插件可以直接搜索安装 image.png

配置页面: image.png image.png

由于插件作者定义的缓存路径是 /var/run/nginx-cache,而我们指定的缓存路径是 /tmp/wpcache ,所以我们需要修改 WordPress 的默认缓存路径,找到网站根目录下的 wp-config.php 中新增如下代码即可:

//根据实际情况定义缓存的存放路径
define( 'RT_WP_NGINX_HELPER_CACHE_PATH','/tmp/wpcache');

总结

一个网站是否高质量,最低要求就是访问速度必须要快,本文介绍的Nginx fastcgi_cache缓存,是基于Nginx为页面生成缓存来加速WorkPress,而且还支持html伪静态页面,效率比使用PHP缓存插件要高得多,速度得到了质的飞跃(提速1倍,600ms响应),这种适合低配置的海外服务器,优化起来就好像国内服务器一样的速度了。

文章原创:光速博客(gsbk.org),禁止转载!

回到顶部