用nginx的rewrite分离WordPress静态文件

wordpress和其主题包含的静态文件(js\css\png\jpg等)比较多,有时写的文章包含的截图也不少,为了降低访问延时,可以分离静态文件是其走CDN加速。wordpress的静态文件存在于主题、插件等目录。单独清理出来还是挺麻烦的,所以用nginx的rewrite规则结合文件后缀达到分离的目的。步骤如下:
1、配置CDN的回源站点xx.xiaomastack.com,该站点根目录/opt/www/f为www.xiaomastack.com站点根目录/opt/www/myblog的软链接,相当于一个镜像。

[root@iZ28vzyqqtfZ conf.d]# cat xx.xiaomastack.com.conf 
server
{
	listen  80;
        server_name  xx.xiaomastack.com;
        index  index.html index.htm;
        root  /opt/www/f;
	
	location / {
            	root  /opt/www/f;
	}

	location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
		expires 10d;
	}
	location ~ .*\.(css|js|map)$ {
		expires 30d;
	}
	
	location ~ \.php$
        {
            root           /opt/www/f;
            fastcgi_pass   unix:/var/run/php-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        access_log  /opt/log/nginx/f2.xiaomastack.com.log main;
}
[root@iZ28vzyqqtfZ conf.d]# ll /opt/www/f
lrwxrwxrwx 1 root root 6 Oct 28 14:33 /opt/www/f -> myblog
[root@iZ28vzyqqtfZ conf.d]#

2、配置www.xiaomastack.com重写规则,使静态文件请求重定向到f.xiaomastack.com加速域名。

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico|ttf|woff)$ {
	rewrite ^/(.*) http://f.xiaomastack.com/$1 permanent;
	expires 10d;
}
location ~ .*\.(css|js|map)$ {
	rewrite ^/(.*) http://f.xiaomastack.com/$1 permanent;
	expires 30d;
}

3、配置CDN,加速域名是f.xiaomastack.com,回源域名是xx.xiaomastack.com。然后将CDN厂商分配CNAME解析到加速域名f.xiaomastack.com即可。
文章出处:http://www.xiaomastack.com/2015/11/03/nginx-rewrite/

发表评论:

你的电子邮件地址将不会被公开.

8 × = 40