WordPress设置静态资源域名,减少cookie请求

近日,在GTmetrix对我辈博客进行测评时,Use cookie-free domains项得分较低(45分),官方解释为“Server static content from a different domain to avoid unnecessary cookies traffic.”,同时给出的建议为“To work around this problem, make sure that static components are requested with cookie-free requests by creating a subdomain and hosting them there. If your domain is domain is www.example.org, you can host your static components on static.example.org. However, if you've already set cookies on the top-level domain example.org as opposed to www.example.org, then all requests to static.example.org will include those cookies. In this case you can buy a whole new domain, host your static components there, and keep this domain cookie-free.”

我辈博客就是采用example.org形式的,所以只能把静态资源设置到其它域名上,这里我是设置为res.minzulou.cn(右击我辈博客中的图片查看链接地址可以发现是以res.minzulou.cn开头的)。下面以我辈博客为例,分享下我的设置方法。

一、设置域名解析

把res.minzulou.cn解析到服务器IP上。

二、配置function.php

将下面内容中的域名修改成自己后添加到function.php中适当位置

对于未开启HTTPS的博客

  1. //==== 静态域名替换函数 ====  
  2. ob_start("Static_Switch");  
  3. function Static_Switch($buffer){  
  4.      $buffer_out = preg_replace('/http:\/\/wobeibk\.com\/wp-([^"\']*?)\.(jpg|png|gif|css|js|woff|woff2|ttf|svg|eot)/i','http://res.minzulou.cn/wp-$1.$2',$buffer);  
  5.      return $buffer_out;  
  6. }  

对于已经开启HTTPS的博客

  1. //==== 静态域名替换函数 ====  
  2. ob_start("Static_Switch");  
  3. function Static_Switch($buffer){  
  4.      $buffer_out = preg_replace('/https:\/\/wobeibk\.com\/wp-([^"\']*?)\.(jpg|png|gif|css|js|woff|woff2|ttf|svg|eot)/i','https://res.minzulou.cn/wp-$1.$2',$buffer);  
  5.      return $buffer_out;  
  6. }  

三、配置wp-config

将下面内容中的域名修改成自己后添加到wp-config中适当位置

  1. /** 指定cookies的域名为网站主域名 */  
  2. define('COOKIE_DOMAIN', 'wobeibk.com');  

修改完成后登录自己的博客查看一下效果吧。

管理员

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: