centos如何添加CDN?
美国、香港服务器
centos如何添加CDN?
11-12 来源:
# 一、整体流程(通用)
1. CDN 平台添加域名,设置**源站 IP = 你的 CentOS 服务器公网 IP**,回源端口 80/443
2. 域名 DNS 改成 CDN 的 NS 记录 / CNAME 记录
3. 服务器防火墙(firewalld / 安全组)**只放行 CDN 回源 IP 段访问 80、443**(禁止直连源站 IP,防绕过 CDN)
4. Nginx 配置 realip 模块,拿到真实访客 IP(日志、WAF、登录限制才正常)
5. 配置缓存规则、HTTPS、证书
# 二、CentOS Nginx 命令行配置(Cloudflare)
先确认模块:
nginx -V | grep realip
有 `--with-http_realip_module` 才支持,宝塔默认自带。
编辑 nginx.conf 或者站点 conf:
vi /usr/local/nginx/conf/nginx.conf
放到 http {} 里面:
# Cloudflare回源IP段,定期更新
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f24b::/32;
# 取真实IP,CF推荐 CF-Connecting-IP
real_ip_header CF-Connecting-IP;
real_ip_recursive on;
检查 + 重载:
nginx -t
systemctl reload nginx
## firewalld 只允许 CF 回源 IP 访问 80/443(关键,防止绕过 CDN)
# 示例:先拒绝所有访问80,再放行CF段
firewall-cmd --permanent --remove-service=http
firewall-cmd --permanent --remove-service=https
firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="104.16.0.0/13" port protocol="tcp" port="80" accept"
firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="104.16.0.0/13" port protocol="tcp" port="443" accept"
firewall-cmd --reload
# 三、宝塔面板方案
1. 网站 → 设置 → 反向代理 / CDN:**CDN 来源 IP 头选择 CF-Connecting-IP**
2. 防火墙:添加 CF 全部 IP 段白名单;**删除 80、443 全局放行**,只允许 CF 回源 IP 访问
3. Nginx 防火墙 / WAF:白名单填入 CF IP 段,避免误封 CDN 节点
4. SSL:两种模式
- 模式 A:CF 上申请证书,回源 HTTP(源站 80)
- 模式 B:源站 443 装证书,CF 选【严格 SSL】(Full (strict)),外贸推荐这个
# 四、缓存规则(Nginx 静态缓存,配合 CDN)
站点 server 块内添加,静态资源缓存,后台、动态页面不缓存:
```
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|webp)$ {
expires 7d;
add_header Cache-Control "public";
}
# 后台、动态程序禁止缓存
location ~ /wp-admin/ {
expires -1;
add_header Cache-Control "no-cache";
}
# 五、验证是否生效
# 看日志里是不是访客真实IP,不是CF节点IP
tail -f /www/wwwlogs/你的域名.log
# 查看域名解析是否走到CDN
nslookup 你的域名
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快