共計 2051 個字符,預計需要花費 6 分鐘才能閱讀完成。
未備案的網站使用 國內 CDN 加速 的方法
1. 首先,使用記事本打開網站的配置文件,并在配置文件中添加以下配置;
server
{
listen 80;
# HTTPS 配置略
server_name static.beiandomain.com; # 改成你實際已備案的二級域名(這個就是新建主機時綁定的域名)
index index.html index.htm index.php default.html default.htm default.php;
root /data/wwwroot/yourwebsitedomain.com; # 需要CDN 加速的網站
# 圖片等靜態資源請求代理到本地主站(關鍵配置)
location ~* .*\.(js|css|png|jpeg|jpg|bmp|ico|ogg|ogv|svg|svgz|eot|otf|woff|woff2|mp4|ttf|rss|atom|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
add_header Access-Control-Allow-Origin *; # 解決字體跨站問題
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,OPTIONS;
proxy_pass http://127.0.0.1; # 如果是啟用了 https 的網站,這里最好改成 https://127.0.0.1, 避免主站加了非 https 協議的跳轉配置,導致不成功。
proxy_set_header X-Forwarded-For $remote_addr;
proxy_redirect off;
proxy_set_header Host yourwebsitedomain.com; # 這里改為實際主站域名(必須)
expires max; # 設置瀏覽器 304 緩存為最長期限
}
# 為這個二級域名額外設置一個 robots 文件
location ~ (robots.txt) {
rewrite /robots.txt /resrobots.txt last; # 在網站根目錄新增一個 resrobots.txt,內容和七牛 CDN 類似,禁止搜索引擎抓取非靜態資源(怎么寫接著看下面)
}
# 如果通過靜態域名訪問的是非靜態資源,比如訪問了我們的文章頁面,則跳到主站對應的頁面。
location / {
if ($request_uri !~* .*\.(js|css|png|jpeg|jpg|gif|bmp|ico|ogg|ogv|svg|svgz|eot|otf|woff|woff2|mp4|ttf|rss|atom|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf))
{
rewrite ^(.*)$ $scheme://yourwebsitedomain.com$1 permanent; # yourwebsitedomain.com 修改為實際主站域名
}
}
location ~ /\. {deny all; access_log off; log_not_found off;}
access_log off;
}
2. 網站配置文件修改好后,在網站根目錄中添加一個 resrobots.txt 文件;
User-agent: *
Allow: /robots.txt
Allow: /wp-content/
Allow: /*.png*
Allow: /*.jpg*
Allow: /*.jpeg*
Allow: /*.gif*
Allow: /*.bmp*
Allow: /*.ico*
Allow: /*.js*
Allow: /*.css*
Disallow: /
3. 最后,resrobots.txt 文件添加好后,在 functions.php 文件中添加 cdn 代理即可;
function QiNiuCDN(){
function Rewrite_URI($html){
$domain = 'yourwebsitedomain\.com'; // 填寫主站域名,小數點前需要加上反斜杠轉義
$static = 'res.zgboke.com'; // 填寫二級靜態域名(使用第三方的 CDN 加速后, 這里需要替換成你 CDN 的名字, 而原來已備案的二級域名則為源站)
// 更多靜態資源需要替換,可以將后綴加到后面的括號,使用分隔符分割
$html = preg_replace('/http(s|):\/\/'.$domain.'\/wp-([^"\']*?)\.(jpg|png|gif|bmp|jpeg|css|js)/i','//'.$static.'/wp-$2.$3',$html);
return $html;
}
if(!is_admin()){
ob_start("Rewrite_URI");
}
}
add_action('init', 'QiNiuCDN');
丸趣 TV 網 – 提供最優質的資源集合!