nginx将.js .css处理为text/plain
1.问题
在使用Django+uwsgi+nginx部署过程中会遇到如下问题,使用Django处理静态文件,运行
python manage.py runserver
可以加载.js、.css文件。部署时将DEBUG = True
改为DEBUG = False
以后Django不再处理静态文件此时需要以下命令
python manage.py collectstatic
在settings.py
中设置STATIC_ROOT
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')
将所有的静态文件收集到collected_static
文件夹下
在nginx配置中添加
location /static {
# alias /path/to/your/mysite/static; # your Django project's static files - amend as required
alias /mysite/collected_static;
expires 1d;
}
ps:alias与root的区别:
alias对应路径/mysite/collected_static
root对应路径/mysite/colletcted_static/static
此时通过浏览器可以发现可以加载网页,但是样式全没了,只有文字
通过chrome的调试功能可以发现,浏览器将.css与.js文件处理为text/plain了
2.解决方案
在nginx的配置文件中添加以下命令
include /etc/nginx/mine.types
location ~ \.js {
add_header Content-Type application/x-javascript;
}
location ~ \.css {
add_header Content-Type text/css;
}
同时清空浏览器缓存,建议在chrome调试的时候勾选Disable cache