确保已安装Nginx(建议1.7.3以上版本):
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
http {
# 定义上游服务器(源站)
upstream origin_server {
server origin.example.com:80;
}
server {
listen 80;
server_name cdn.example.com;
location / {
proxy_pass http://origin_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
http {
# 缓存路径配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
upstream origin_server {
server origin.example.com:80;
}
server {
listen 80;
server_name cdn.example.com;
location / {
proxy_cache my_cache;
proxy_pass http://origin_server;
# 缓存相关配置
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 1m;
proxy_cache_key "$scheme://$host$request_uri";
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
# 添加缓存状态头信息(调试用)
add_header X-Cache-Status $upstream_cache_status;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:100m inactive=24h max_size=10g
use_temp_path=off;
# 定义不同文件类型的缓存时间
map $uri $cache_time {
~*\.(jpg|jpeg|png|gif|ico|css|js)$ "30d";
default "1h";
}
server {
# ...其他配置...
location / {
proxy_cache my_cache;
proxy_pass http://origin_server;
# 动态设置缓存时间
proxy_cache_valid 200 304 $cache_time;
proxy_cache_valid any 5m;
# 缓存锁定(防止多个请求同时回源)
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
# 忽略源站设置的缓存头
proxy_ignore_headers Cache-Control Set-Cookie;
proxy_hide_header Set-Cookie;
# 其他配置...
}
}
}
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
proxy_cache_purge my_cache "$scheme://$host$1";
}
upstream origin_server {
server origin1.example.com:80 weight=3;
server origin2.example.com:80;
server origin3.example.com:80 backup;
# 健康检查
check interval=3000 rise=2 fall=5 timeout=1000;
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_vary on;
server {
# ...其他配置...
# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 防止盗链
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
valid_referers none blocked cdn.example.com ~.google. ~.bing. ~.yahoo.;
if ($invalid_referer) {
return 403;
}
}
# 限制连接数
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn perip 100;
# 隐藏Nginx版本号
server_tokens off;
}
sudo nginx -t
sudo systemctl reload nginx
curl -I http://cdn.example.com/some-resource.jpg
# 查看响应头中的X-Cache-Status字段
grep -E "HIT|MISS|EXPIRED" /var/log/nginx/access.log | awk '{print $NF}' | sort | uniq -c
find /var/cache/nginx -type f -delete
awk '{print $NF}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
通过以上配置,您已经成功搭建了一个基本的CDN服务器。根据实际需求,您可以进一步调整缓存策略、添加更多边缘节点或集成其他CDN功能。