Django部署AWS+Nginx环境静态文件加载失败求助
Django部署到AWS+Nginx后静态文件无法加载的问题排查与解决
问题描述
本地运行正常的Django网站,部署到AWS+Nginx生产环境后静态文件无法加载。已设置DEBUG=False,安装了whitenoise==6.2.0,调整过Nginx路径配置但问题仍未解决。
报错信息

Django配置(settings.py)
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://54.234.143.251", ] CSRF_TRUSTED_ORIGINS = [ "http://54.234.143.251", ] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # app "applipsync", "store", # packages "whitenoise.runserver_nostatic", "rest_framework", "django_q", "allauth", "allauth.account", "allauth.socialaccount", "crispy_forms", ] CRISPY_TEMPLATE_PACK = "bootstrap4" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "core.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "core.wsgi.application" # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_REQUIRED = True # Make email verification mandatory to avoid junk email accounts ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ] LOGIN_REDIRECT_URL = "/" ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True # settings.py example Q_CLUSTER = { "name": "pdm", "workers": 1, "recycle": 500, "timeout": 60, "retry": 120, "compress": True, "save_limit": 250, "queue_limit": 500, "cpu_affinity": 1, "label": "Django Q", "daemonize_workers": False, "orm": "default", } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) # PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) # STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root print("BASE_DIR ", BASE_DIR) print("------------------------------------------") print(STATIC_ROOT) # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), "templates").replace("\\", "/"), )
AWS文件路径

Nginx配置
server { listen 80; server_name 54.234.143.251; client_max_body_size 100M; sendfile on; # to avoid any error while fetching fevicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/ubuntu/lipsync-website/app/staticfiles/; } location /media/ { autoindex on; alias /home/ubuntu/lipsync-website/app/media/; } location / { # communicate via socket file created by Gunicorn # proxy_pass http://unix:/home/ubuntu/lipsync-website/app/core.sock; proxy_pass http://0.0.0.0:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } }
网站显示效果
- 当前显示效果:

- 预期显示效果:

排查与解决步骤
1. 确认静态文件已正确收集
进入AWS服务器的项目根目录,运行python manage.py collectstatic,确保所有静态文件被收集到STATIC_ROOT指定的staticfiles目录。执行后检查/home/ubuntu/lipsync-website/app/staticfiles/下是否存在css、js等静态资源文件。
2. 验证Nginx路径与权限
- 核对Nginx配置中
alias路径是否与服务器实际路径完全匹配,确认/home/ubuntu/lipsync-website/app/staticfiles/目录真实存在; - 给静态文件目录添加可读权限:执行
sudo chmod -R 755 /home/ubuntu/lipsync-website/app/staticfiles/,确保Nginx进程能读取该目录下的文件; - 重启Nginx使配置生效:执行
sudo systemctl restart nginx。
3. 完善Whitenoise配置
在settings.py中添加以下配置,确保Whitenoise正确处理静态文件的缓存与压缩:
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
4. 检查浏览器请求路径
打开浏览器开发者工具(F12),查看网络请求中静态文件的URL是否正确(例如http://54.234.143.251/static/css/main.css),并确认该文件在服务器staticfiles目录下存在对应路径。
5. 选择静态文件处理方式(二选一)
- 用Nginx处理静态文件:确保Nginx的
location /static/配置正确,且静态文件已收集到位; - 用Whitenoise处理静态文件:删除Nginx中
location /static/的配置块,让请求转发给Django,由Whitenoise提供静态文件。
内容的提问来源于stack exchange,提问作者Muhammad Kamal
相关产品推荐
相关产品推荐

