WordPress使用二级域名动静分离

好处

使用CDN以后,要加速静态资源,最好将静态资源都放在一个单独的二级域名下,比如“static.botailang.com”,这样CDN只加速这一个域名下的图片等文件,网页文件从主站下载,就能大大减轻带宽的压力。

方法

假如主域名和静态文件域名分别为www.botailang.com和static.botailang.com,需要完成下面几件事情。

如果开启https访问,并且不支持泛域名,需要为静态文件域名申请一个证书。

网站配置

静态文件域名和主域名分别配置nginx站点,并且设置为相同的根目录

静态文件域名配置:

server
{
        listen 443 ;
        server_name     static.botailang.com;
        root            /home/wwwroot/botailang.com;
 
        ssl on;
        ssl_certificate       /etc/letsencrypt/live/botailang.com/fullchain.pem;
        ssl_certificate_key   /etc/letsencrypt/live/botailang.comm/privkey.pem;
        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
 
        location ~* .*\.(gif|jpg|jpeg|png|bmp)?$ {
            set $width '';
            set $height '';
            set $width $arg_width;
            set $height $arg_height;
            if ( $width != '' ) {
                add_header Thumbnail "By Nginx";
            }
            if ( $height = '' ) {
                set $height '-';
            }
            if ( $width = '' ) {
                set $width '-';
                set $height '-';
            }
            image_filter resize $width $height;
            image_filter_buffer 2M;
            image_filter_jpeg_quality 80;
            image_filter_transparency on;
            expires max;
            access_log off;
        }
 
        location ~ .*\.(eot|otf|ttf|woff|woff2)?$ {
            add_header Access-Control-Allow-Origin *;
            expires max;
            access_log off;
        }
 
        location ~ .*\.(js|css)?$ {
            expires      12h;
            access_log   off;
        }
 
        location = /robots.txt {
            deny all;
        }
 
        access_log /home/wwwlogs/static.botailang.com.log;
}

需要注意的几点:

root 指令需要设成和主域名一样的根目录
location ~* .*\.(gif|jpg|jpeg|png|bmp)?$的指令里利用image_filter来生成缩略图,缩略图处理必须在静态资源域名下处理。
location ~ .*\.(eot|otf|ttf|woff|woff2)?$的指令里要记得加上Access-Control-Allow-Origin的http头部,不然会出现字体加载的跨域错误。
location = /robots.txt的指令里禁止搜索引擎爬虫抓取。
然后是主域名的nginx配置,这里重点是将所有静态资源的处理都移到了二级域名去处理,因此只留下了动态资源处理和fastcgi缓存的部分。

主域名配置:

网站根目录和静态文件域名的一样。

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;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
 
server
    {
        listen 443 default;
        #listen [::]:80;
        server_name www.botailang.com botailang.com;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/234du.com;
 
        if ($host = 'feiqy.com') {
            rewrite ^(.*)$  https://www.botailang.com$1 permanent;
        }
 
        ssl on;
        ssl_certificate       /etc/letsencrypt/live/botailang.com/fullchain.pem;
        ssl_certificate_key   /etc/letsencrypt/live/botailang.com/privkey.pem;
        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
 
        set $skip_cache 0;
        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 ~ [^/]\.php(/|$)
            {
                try_files $uri =404;
                fastcgi_pass  unix:/tmp/php-cgi.sock;
                fastcgi_index index.php;
                include fastcgi.conf;
                fastcgi_cache_bypass $skip_cache;
                fastcgi_no_cache $skip_cache;
                add_header X-Cache "$upstream_cache_status From $host";
                fastcgi_cache WORDPRESS;
                fastcgi_cache_valid 200 301 302 1d;
        }
        location / {
                try_files $uri $uri/ /index.php?$args;
                rewrite /wp-admin$ $scheme://$host$uri/ permanent;
        }
 
        location ~ /.well-known {
            allow all;
        }
 
        location /xmlprc.php {
            deny all;
        }
 
        location = /robots.txt { access_log off; log_not_found off; }
        location ~ /\. { deny  all; access_log off; log_not_found off; }
 
        access_log /home/wwwlogs/www.botailang.com.log;
    }

重写静态资源URL

一种考虑是通过直接修改数据库所有静态资源URL,全部批量替换为static.botailang.com开头,那么以后新的文章还是不能自动变成二级域名,网上查到一种方法是通过修改wordpress某个地方,暴露出设置选项能全局修改媒体库的URL,这种方法我没有尝试。

另一种方法是直接在主题的代码中自动重写所有静态资源的域名,一劳永逸而且随时可以改成别的域名。
将下面的代码加入主题中functions.php,放在 ?>前面。
这样在网页中所有的静态资源(jpg,js,css,gif,png,jpeg,woff)都自动地替换成为static开头的域名。如果有需要还可以加入其它种类的资源,比如ttf,mp4等文件。

function QiNiuCDN(){
    function Rewrite_URI($html){
        $pattern ='/https:\/\/(www\.|)botailang\.com\/wp-([^"\']*?)\.(jpg|js|css|gif|png|jpeg|woff)/i';
        $replacement = 'https://static.botailang.com/wp-$2.$3';
    $html = preg_replace($pattern, $replacement,$html);
    return $html;
    }
    if(!is_admin()){
        ob_start("Rewrite_URI");
    }
}
add_action('init', 'QiNiuCDN');

在wp-config.php里定义COOKIE_DOMAIN 常量来限制cookie的作用域,因此当浏览器加载静态资源域名里的内容时,request header里不会带有主域名的cookie,节约了传输带宽,达到提高加载速度的目的。

define('COOKIE_DOMAIN', 'www.botailang.com');

本文转载:

https://www.feiqy.com/wordpress-static-separation/