Ubuntu 环境下配置缓存与 CDN 加速
一 架构与总体思路
二 方案一 使用 CDN 加速静态资源(以 Vue/React 等前端项目为例)
server {
listen 80;
server_name your-domain.com;
root /path/to/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, must-revalidate";
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
三 方案二 使用 Nginx 作为反向代理缓存(无独立 CDN 或做源站加速)
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=cdn_cache:10m
max_size=1g inactive=60m use_temp_path=off;
proxy_cache_key "$scheme$request_method$host$request_uri";
}
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://127.0.0.1:8080; # 你的上游服务
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_cache cdn_cache;
proxy_cache_valid 200 7d;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
}
}
四 方案三 使用 Apache2 作为反向代理缓存(可选)
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot /var/cache/apache2/mod_cache_disk
CacheEnable disk /static/
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
</IfModule>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
<IfModule mod_proxy.c>
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
</IfModule>
五 缓存策略与运维要点