使用Varnish从内存加速你的WordPress网站 - AFF大佬 - 提供主机优惠信息深度测评和服务器运维编程技术
当前位置: 主页 » 技术干货 » 使用Varnish从内存加速你的WordPress网站

使用Varnish从内存加速你的WordPress网站

      2019年04月29日   阅读 465 次     2 评论   Tags: · ·

也许大家都听过Varnish,Varnish是基于内存来减少数据库的增删改查来加速网站,另一个是squid,常见CDN必备软件,基于文件,也就是硬盘的,经过我的测试,本站运行在OVH 李家坡,配置1核1G内存30GSSD硬盘,可以达到500并发2000次请求,在5S内完成,性能相当优异。

UPDATE:20.19/5/3,更新Varnish配置文件,解决评论被缓存的问题。
UPDATE:20.19/5/24,更新Varnish密钥和varnish管理。

1、实验需求:Centos7 +Varnish 6.2(最新版)+Nginx1.15.12 ,全部是最新版



1.1安装Varnish 
curl -s https://packagecloud.io/install/repositories/varnishcache/varnish62/script.rpm.sh | sudo bash

yum install varnish -y

2、配置Varnish,Varnish的配置文件在/etc/varnish/default.vcl



vcl 4.0; /* 定义ACL版本 */


backend default {  
  .host = "127.0.0.1";
  .probe = {   /* 健康检测 */
        .url = "/";
        .timeout = 1s;
        .interval = 5s;
        .window = 5;
        .threshold = 3;
    }
  .port = "8081";           
  .connect_timeout = 600s;
  .first_byte_timeout = 600s;
  .between_bytes_timeout = 600s;
  .max_connections = 128;
}



acl purger {  /* 允许清理缓存的主机 */
   "localhost";
   "127.0.0.1";
}


sub vcl_backend_error {    /* 自定义503错误 */
    if (beresp.status == 503){
        set beresp.status = 200;


	set beresp.http.Content-Type = "text/html; charset=utf-8";
	set beresp.http.Retry-After = "5";

	synthetic( {"

  
	"} + beresp.status + " " + beresp.reason + {"
  
  
    

Error:Backend has no response."} + " " + {"

Guru Meditation:

XID: "} + bereq.xid + {"


CDN BY CdnTiger.com, CacheServerID: "} + server.hostname + {"

"} ); return (deliver); } } sub vcl_recv { if (req.method == "PURGE") { if (!client.ip ~ purger) { return(synth(405, "This IP is not allowed to send PURGE requests.")); } return (purge); } if (req.restarts == 0) { if (req.http.X-Forwarded-For) { set req.http.X-Forwarded-For = client.ip; } } if (req.http.Authorization || req.http.Cookie ~ "wordpress_logged" || req.http.Cookie ~ "comment_") { /* 设置不缓存规则 */ return (pass); } if (req.url ~ "/feed") { return (pass); } if (req.url ~ "wp-admin|wp-login|user/login/") { return (pass); } if (req.url ~ "^(.*)\.(jpg|png|gif|jpeg|flv|bmp|gz|tgz|bz2|tbz|js|css|html|htm)($|\?)" ) { #移除cookie,以便能缓存到varnish unset req.http.cookie; } set req.http.cookie = regsuball(req.http.cookie, "wp-settings-\d+=[^;]+(; )?", ""); set req.http.cookie = regsuball(req.http.cookie, "wp-settings-time-\d+=[^;]+(; )?", ""); if (req.http.cookie == "") { unset req.http.cookie; } } sub vcl_purge { set req.method = "GET"; set req.http.X-Purger = "Purged"; return (restart); } sub vcl_backend_response { /* 开启grace模式,在cache过期后的15 秒内,使用旧的内容提供服务,全部缓存2小时 */ set beresp.ttl = 2h; set beresp.grace = 15s; if (bereq.url !~ "wp-admin|wp-login|product|user/login/|cart|checkout|my-account|/?remove_item=") { unset beresp.http.set-cookie; } } sub vcl_deliver { unset resp.http.Via; unset resp.http.X-Varnish; unset resp.http.Server; /* 增加cache http头部,x-cache定义 varnish是否名字 */ if (obj.hits > 0) { set resp.http.X-Cache = "HIT from " + server.hostname; } else { set resp.http.X-Cache = "MISS from " + server.hostname; } }

3、配置varnish管理秘钥


/usr/bin/uuidgen > /etc/varnish/secret
chmod 644 /etc/varnish/secret

4、Varnish运行配置:vi /usr/lib/systemd/system/varnish.service



说明:6081为varnish运行端口,default.vcl为varnish运行配置文件,128m为varnish运行内存,根据机器配置可适当调整,内存方式和文件方式运行二选一。

#以内存方式运行 ' malloc,128m ',分配128M内存运行Varnish。
ExecStart=/usr/sbin/varnishd -a :6081 -f /etc/varnish/default.vcl -s malloc,128m  -S /etc/varnish/secret

#以文件方式运行 ' file,/tmp/varnish/cache.bin,5G ',分配5G文件运行Varnish。
ExecStart=/usr/sbin/varnishd -a :6081 -f /etc/varnish/default.vcl -s file,/tmp/varnish/cache.bin,5G  -S /etc/varnish/secret

ExecReload=/usr/sbin/varnishreload

4、Varnish管理命令


###查看varnish缓存命中率,按q键退出
varnishstat
###管理varnish缓存
varnishadm -S /etc/varnish/secret -T 127.0.0.1:6081

###查看varnish log
打印日志到一个文件:
varnishlog -w /var/log/varnish.log
读取一个日志文件,然后显示请求的首页:
varnishlog -r /var/log/varnish.log -c -o RxURL '^/$' 

5、配置nginx文件



[root@vps219051 ~]# cat /etc/nginx/conf.d/affdalao.conf
server {
    listen 80;
    server_name  www.affdalao.com affdalao.com;
 
    rewrite ^/(.*) https://www.affdalao.com/$1 permanent;
}


server {
        listen 443 ssl http2 fastopen=3 reuseport;

	server_name  www.affdalao.com affdalao.com;

	error_log  /var/log/nginx/error.log  crit;
        ssl_certificate      /etc/letsencrypt/live/affdalao.com/fullchain.pem;
        ssl_certificate_key  /etc/letsencrypt/live/affdalao.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/affdalao.com/chain.pem;
	ssl_dhparam /etc/nginx/ssl/dhparam.pem;

	ssl_protocols TLSv1.2;
	ssl_prefer_server_ciphers on;

	ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";


	
	ssl_session_cache shared:SSL:10m;
	ssl_session_timeout 10m;

	
	# OCSP Stapling ---
	# fetch OCSP records from URL in ssl_certificate and cache them
	ssl_stapling on;
	ssl_stapling_verify on;

        location / {
            proxy_pass http://127.0.0.1:6081;   
            #Varnish监听端口为6081,注意防火墙一定不要开启此端口,防火墙对外开启80 443和需要的端口即可。
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
            proxy_set_header X-Forwarded-Port 443;
            proxy_set_header Host $host;
        }

}

    server {
        listen 8081;
        #注意防火墙一定不要开启此端口8081,防火墙对外开启80 443和需要的端口即可。
        server_name  affdalao.com;
	port_in_redirect off;


    location / {
        root   /home/affdalao;
        index   index.php index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
   
    }


       error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ .*\.php(\/.*)*$ {
        root           /home/affdalao;
       fastcgi_index index.php;
       fastcgi_param HTTPS on;

	fastcgi_pass   unix:/dev/shm/php7-fpm.sock;
        fastcgi_param  SCRIPT_FILENAME  /home/affdalao$fastcgi_script_name;
        include        fastcgi_params;
    }
}


6、配置wp-config.php顶部加入一些代码,开启HTTPS支持


if ($_SERVER['HTTP_X_SSL'] == 'on') $_SERVER['HTTPS']='on';


7、在浏览器查看缓存是否命中,第一次可能varnish没有生效,可以多刷新几次查看是否命中

8、使用varnish自带命令:varnishstat查看是否命中缓存:MAIN.cache_hit命中数量/MAIN.cache_miss未命中数量

9、使用AB命令对网站进行压力测试:ab -n 2000 -c 500 https://www.affdalao.com/index.php

至此Varnish配置完毕,可以卸载那些缓存的插件了。

  • 版权声明:本文版权归AFF大佬和原作者所有,未经许可不得转载。文章部分来源于网络仅代表作者看法,如有不同观点,欢迎进行交流。除非注明,文章均由 AFF大佬 整理发布,欢迎转载,转载请带版权。

  • 来源:AFF大佬 ( https://www.affdalao.com/ ),提供主机优惠信息深度测评和服务器运维编程技术。
  • 链接:https://www.affdalao.com/593.html
  • 评论(2

    1. cad.cc说道:

      学习了。谢谢

    发表评论

    电子邮件地址不会被公开。 必填项已用*标注