Fix Django Static Files Not Loading in Production (Nginx + Gunicorn)
If your Django site loads but CSS is missing, JavaScript is broken, or the admin panel looks unstyled, then your static files are not being served correctly. This guide will help you fix it step-by-step.
If your Django site loads but:
- CSS is missing
- JavaScript is broken
- Admin panel looks unstyled
π Then your static files are not being served correctly
This guide will help you fix it step-by-step.
β‘ Quick Fix (Try This First)
Run:
python manage.py collectstatic
sudo systemctl restart gunicorn
sudo systemctl restart nginx
Then reload your site.
π This solves the issue in many cases.
π§ Whatβs Happening
In production:
- Django does NOT serve static files
- Nginx is responsible for serving them
If static files are broken, it usually means:
Nginx cannot find or access your static files
π§ͺ Step-by-Step Diagnosis
Follow these steps in order.
1. Check STATIC_ROOT setting
In settings.py:
STATIC_ROOT = '/var/www/myproject/static/'
π This is where files will be collected
2. Run collectstatic command
python manage.py collectstatic
Verify files exist:
ls /var/www/myproject/static/
You should see:
admin/css/js/
π If empty β static files were not collected
3. Check Nginx configuration
Open your config:
sudo nano /etc/nginx/sites-available/myproject
or your favourite editor.
Ensure this exists:
location /static/ {
root /var/www/myproject;
}
π Important:
root must match your STATIC_ROOT parent directory
/static/ maps to /var/www/myproject/static/
4. Test Nginx config
sudo nginx -t
Then:
sudo systemctl restart nginx
5. Test static file directly
Open in browser:
http://your-domain/static/admin/css/base.css
If it works:
- Nginx is correct
If NOT:
- Problem is Nginx or file path
6. Check file permissions
sudo chown -R www-data:www-data /var/www/myproject
sudo chmod -R 755 /var/www/myproject
This will fix permissions for all files in the directory.
π Nginx must be able to read the files
π₯ Common Causes (and Fixes)
π΄ Forgot to run collectstatic
Fix:
python manage.py collectstatic
π΄ Wrong STATIC_ROOT
Make sure:
- Matches Nginx path
- Is an absolute path
π΄ Nginx misconfiguration
Wrong:
root /var/www/myproject/static;
Correct:
root /var/www/myproject;
π΄ DEBUG = False but no static setup
In production:
DEBUG = False
π Django stops serving static files
π΄ Permissions issue
Fix:
sudo chown -R www-data:www-data /var/www/myproject
π΄ Wrong STATIC_URL
In settings.py:
STATIC_URL = '/static/'
π§ Debugging Tips
Check Nginx logs:
sudo tail -f /var/log/nginx/error.log
Look for:
- 404
- permission denied
Check browser console:
- Open DevTools β Network tab
- Look for:
- 404 errors
- missing files
β Quick Fix Checklist
Compare your setup with the full Nginx + Gunicorn deployment guide and finish with the production checklist.