Django项目中Gunicorn搭配Apache服务器无法加载静态文件,出现404及MIME类型错误
Django项目中Gunicorn搭配Apache服务器无法加载静态文件,出现404及MIME类型错误
我在使用Gunicorn和Apache(mod_wsgi)运行Django项目时,静态文件无法被正确加载。加载页面时会出现以下错误:
Not Found: /static/css/style.css
Not Found: /static/js/app.js
浏览器控制台里的错误信息:
Refused to apply style from 'http://localhost/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
另外,当我直接访问静态文件(比如http://localhost:9090/static/css/style.css)时,也会得到404错误。我已经在Django配置里正确设置了静态文件相关项,但Gunicorn就是找不到它们。
环境信息
- Django版本:5.1
- Gunicorn版本:20.x.x
- Apache版本:2.4.x
- mod_wsgi版本:4.9.0
- 操作系统:Ubuntu 20.04
- Python版本:3.10
- 运行在虚拟环境中
Django静态配置(settings.py)
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'app/static')] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'userentry', # my django app ]
当前部署设置
- Apache将请求代理到Gunicorn
- 已经通过
python manage.py collectstatic命令把静态文件收集到了STATIC_ROOT目录 - 我已经确认服务器上的静态文件确实位于
/app/static/路径下
Apache虚拟主机配置
<VirtualHost *:80> ServerAdmin webmaster@localhost ServerName localhost ProxyPass / http://127.0.0.1:9090/ ProxyPassReverse / http://127.0.0.1:9090/ # Point WSGI to the proper directories WSGIDaemonProcess malwarepurge python-home=/app/venv python-path=/app/malwarepurge WSGIProcessGroup malwarepurge WSGIScriptAlias /app /app/malwarepurge/wsgi.py Alias /static/ /app/static/ # Allow access to the necessary app files (including other directories in /app) <Directory /app> AllowOverride All Require all granted </Directory> # Specifically grant access to the malwarepurge folder for WSGI <Directory /app/malwarepurge> AllowOverride All Require all granted </Directory> <Directory /app/static> Require all granted </Directory> <Directory /app/userentry/> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined
已采取的步骤
我已经做了这些操作:
- 在Django设置中添加了STATIC_URL、STATICFILES_DIRS和STATIC_ROOT
- 运行了
python manage.py collectstatic命令把静态文件收集到指定目录 - 配置了Apache使用mod_wsgi来运行Django应用
- Gunicorn正在运行,但无法直接提供静态文件
- 理论上Apache应该负责提供静态文件,但Gunicorn仍然在访问静态文件时返回“Not Found”错误
尝试过的调试方法
我还尝试了这些调试步骤:
- 反复检查STATIC_URL、STATIC_ROOT和STATICFILES_DIRS的配置是否正确
- 确认静态文件确实在
/app/static/路径下 - 修改配置后重启了Apache和Gunicorn
- 验证了静态文件的路径是否正确,以及Gunicorn是否在正确的IP/端口上运行
- 检查了mod_wsgi是否正确安装并启用
备注:内容来源于stack exchange,提问作者Shelbert Miller
相关产品推荐
相关产品推荐

