静态文件必须由 Nginx 直接服务,禁用 Python 框架处理;需明确路径、授权读取、显式配置 location(alias/root)、添加缓存头、用 try_files 实现 SPA 路由兜底,并确保无静态请求被错误代理至后端。

静态文件必须由 Nginx 直接服务,不能让 Python 框架(如 Flask 的 send_from_directory 或 Django 的开发服务器)去读取并返回。这是性能关键点:Nginx 支持零拷贝(zero-copy)发送文件,而 Python 进程处理静态请求会白白占用 CPU 和工作进程,拖慢整体响应。
明确静态资源路径并授权访问
把前端构建产物(如 dist/、build/ 或 static/)放在服务器上一个固定位置,例如:
-
/var/www/myapp/dist(SPA 前端) -
/var/www/myapp/static(Django/Flask 的 CSS/JS 图片等)
确保该目录对 Nginx worker 用户(通常是 www-data 或 nginx)可读:
sudo chown -R root:www-data /var/www/myapp/dist sudo chmod -R 755 /var/www/myapp/dist
在 server 块中配置静态 location
不要只靠 root 指令兜底;要为静态资源路径显式声明 location 块,并用 alias 或 root 精准映射:
立即学习“Python免费学习笔记(深入)”;
- 用
alias时,结尾斜杠必须匹配:location /static/ { alias /var/www/myapp/static/; }
访问/static/style.css→ 实际读取/var/www/myapp/static/style.css - 用
root时,路径是拼接的:location /dist/ { root /var/www/myapp; }
访问/dist/index.html→ 实际读取/var/www/myapp/dist/index.html
同时加上缓存头,减少重复请求:
location /static/ {
alias /var/www/myapp/static/;
expires 1y;
add_header Cache-Control "public, immutable";
}
启用 try_files 实现前后端分离兜底
对单页应用(Vue/React),所有前端路由都应由 index.html 接收,再交由 JS 路由接管。在根 location 中加:
location / {
root /var/www/myapp/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
这样,访问 /about 时若无真实文件,Nginx 会自动返回 /var/www/myapp/dist/index.html,不转发给后端。
禁止 Python 处理静态路径
在反向代理到 Python 后端(如 Gunicorn)的 location / 或 location /api/ 之外,确保没有其他 location 规则意外将静态请求转给 Python。特别检查:
- 是否误配了
proxy_pass到/static/或/dist/ - Django 的
DEBUG=True开发模式下自动提供静态文件,上线必须关掉并交由 Nginx 托管 - Flask 不应有
@app.route('/static/<path:filename>')类似逻辑用于生产环境
只要路径匹配上静态 location 块,Nginx 就不会把请求交给 upstream,这才是加速的本质。


















