📁 静态资源服务
基本静态文件服务
nginx
server {
listen 80;
server_name example.com;
# root 指定根目录
root /var/www/mysite;
# 默认首页文件
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}root vs alias 的区别
nginx
# root:访问 /images/logo.png → 查找 /var/www/html/images/logo.png
location /images/ {
root /var/www/html;
}
# alias:访问 /images/logo.png → 查找 /var/www/static/logo.png
location /images/ {
alias /var/www/static/;
}💡 提示: 💡 简单记法:root是"在原来路径基础上加",alias是"完全替换"。
启用 Gzip 压缩
Gzip 就像给文件抽真空打包——传输体积变小,速度变快。
nginx
http {
gzip on; # 开启 gzip
gzip_vary on; # 添加 Vary 头
gzip_min_length 1024; # 小于 1KB 不压缩
gzip_comp_level 6; # 压缩级别 1-9(6 是性价比最高)
gzip_types
text/plain
text/css
text/javascript
application/json
application/javascript
application/xml
image/svg+xml;
}缓存控制
nginx
# 静态资源缓存(CSS、JS、图片)
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d; # 缓存 30 天
add_header Cache-Control "public, no-transform";
access_log off; # 不记录日志(减少磁盘 IO)
}
# HTML 文件不缓存(保证用户看到最新版本)
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-store, no-cache, must-revalidate";
}