网络 > 记录:通过nginx设置为站点资源,根据国内国外使用不同的cdn

2017-12-15

目标:加速客户网站访问,使用cdn。

为了效果以及费用考虑,国内的加载阿里云的,国外的加载cloudflare。使用nginx的变量功能实现了这一效果

首先,确认nginx有geoip模块,并下载相应geoip数据

其次,调整nginx.conf的http部分

   geoip_country /GeoIP.dat;
   geoip_city    /GeoLiteCity.dat;
   map $geoip_country_code $cdn {
       default cf;
       CN ali;
   }
然后,调整nginx反代配置,以wordpress为例

       location / {
                       set $cdnpath cfcdn.cfcdn.com;
                     sub_filter_once off;
                       if ($cdn = ali){
                               set $cdnpath alicdn.alicdn.com;
                       }
                       add_header X-Cdn $cdn; 


                       sub_filter '${host}/wp-content/' '$cdnpath/wp-content/';
                       sub_filter '${host}/wp-includes/' '$cdnpath/wp-includes/';
                       sub_filter 'http:\/\/${host}\/wp-content\/' 'http:\/\/${cdnpath}\/wp-content\/';
                       sub_filter 'http:\/\/${host}\/wp-includes' 'http:\/\/${cdnpath}\/wp-includes';
                       sub_filter 'url("/wp-content/' 'url("http://${cdnpath}/wp-content/';
                       sub_filter 'src="/wp-content/' 'src="http://${cdnpath}/wp-content/';
                       sub_filter 'src="/wp-include/' 'src="http://${cdnpath}/wp-include/';
                       proxy_pass         http://127.0.0.1:8080;
                       proxy_set_header   Host $host;
                       proxy_set_header   X-Real-IP  $remote_addr;
                       proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                       proxy_set_header   X-Scheme $scheme;
       }


完成。


点击登录