基于 nginx 搭建 jsdelivr 镜像站

​最近 jsdelivr 可谓国内站长圈的头条常客,这不,又双叒叕(yòu shuāng ruò zhuó)打不开了。

如何解决这个问题?最简单的方法当然是使用别人建立的jsd镜像站,但是稳定性和可靠性就只能看镜像站长的心情了吧。自己动手丰衣足食,还是自己搞个镜像吧。

创建 jsdelivr 镜像站

  • 首先,你需要有一台安装了 nginx 的服务器。

  • 然后,把下面的 nginx 配置保存为 jsdelivr.conf,上传到你的 nginx 站点配置目录中。

server {

    listen 80;

    listen 443 ssl http2;

    # 请更改为你的证书路径
    ssl_certificate certs/default.cer;
    ssl_certificate_key certs/default.key;

    # 请更改为你的镜像域名
    server_name jsd.example.org;

    location / {
        proxy_pass https://cdn.jsdelivr.net;
        proxy_set_header Host $proxy_host;
        proxy_set_header Accept-Encoding '';
        proxy_ssl_server_name on;
        proxy_ssl_name $proxy_host;
        proxy_redirect / /;
        # 缓存设置
        proxy_cache jsdelivr;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 15s;
        proxy_cache_use_stale updating;
        proxy_cache_background_update on;
        proxy_cache_key $host$request_uri;
        proxy_cache_valid 200 301 302 30d;
        proxy_cache_valid 500 501 502 503 15s;
        proxy_cache_valid any 5m;
        # 替换响应内容中的域名
        sub_filter_once off;
        sub_filter_types application/javascript application/json text/xml text/css;
        sub_filter '$proxy_host' '$host';
        # 防盗链设置
        valid_referers none example.org *.example.org;
        if ($invalid_referer) {
            return 403;
        }
    }

}

# 缓存路径请根据需要更改
proxy_cache_path /var/tmp/nginx/jsdelivr levels=1:2 use_temp_path=off keys_zone=jsdelivr:300m inactive=30d max_size=30g;

使用 jsdelivr 镜像站

在你的站点源码中批量替换 cdn.jsdelivr.netjsd.example.org 即可使用自己的jsd镜像了。

当然,也可以把下面的代码插入到你的站点 nginx 配置中,不修改站点源码替换为自己的镜像站。

sub_filter_once off;
sub_filter_types application/javascript application/json text/xml text/css;
sub_filter 'cdn.jsdelivr.net' 'jsd.example.org';
文章作者: 若海; 原文链接: https://www.rehiy.com/post/428/; 转载需声明来自技术写真 - 若海

添加新评论