基于LNMP自建小型CDN的可落地方案
一、方案总览与适用场景
二、方案一 边缘Nginx反向代理缓存 + 源站LNMP
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:100m inactive=7d max_size=10g;
proxy_cache_key "$scheme$request_method$host$request_uri";
server {
listen 80;
server_name cdn.example.com;
# 静态资源:长缓存 + 强缓存策略
location ~* \.(jpg|jpeg|png|gif|webp|svg|css|js|ico)$ {
proxy_pass http://origin_backend;
proxy_cache STATIC;
proxy_cache_valid 200 304 7d;
proxy_cache_valid any 1m;
add_header X-Cache-Status $upstream_cache_status;
expires 30d;
add_header Cache-Control "public, immutable";
}
# 动态内容:回源
location / {
proxy_pass http://origin_backend;
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-Forwarded-Proto $scheme;
proxy_cache_bypass $cookie_nocache $arg_nocache;
}
}
upstream origin_backend {
server 203.0.113.10:80; # 源站Nginx
}
server {
listen 80;
server_name origin.example.com;
root /var/www/html;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000; # PHP-FPM
}
# 静态资源直出(可选:若边缘层未覆盖全部静态路径)
location ~* \.(jpg|jpeg|png|gif|webp|svg|css|js|ico)$ {
expires 30d;
add_header Cache-Control "public";
}
}
三、方案二 Varnish缓存前置 + Nginx回源
vcl 4.0;
import directors;
backend web1 {
.host = "172.25.254.102";
.port = "80";
.probe = {
.url = "/health.html";
.window = 3;
.threshold = 2;
.interval = 3s;
}
}
backend web2 {
.host = "172.25.254.103";
.port = "80";
.probe = {
.url = "/health.html";
.window = 3;
.threshold = 2;
.interval = 3s;
}
}
sub vcl_init {
new web_cluster = directors.round_robin();
web_cluster.add_backend(web1);
web_cluster.add_backend(web2);
}
sub vcl_recv {
if (req.http.host ~ "^(www\.)?example\.com$") {
set req.http.host = "www.example.com";
set req.backend_hint = web_cluster.backend();
# 如需强制回源调试可打开:return(pass);
} else {
return(synth(404, "Not in cache"));
}
}
四、DNS智能解析与回源HOST配置
五、缓存策略与运维要点