Проблема с загрузкой статических файлов и изображений с Amazon S3 в Django
# Amazon S3 Configuration
AWS_ACCESS_KEY_ID = "<your-access-key-id>"
AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>"
AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>"
AWS_S3_REGION_NAME = "us-east-2"
AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com"
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_S3_QUERYSTRING_AUTH = False
# STORAGES Configuration
STORAGES = {
"default": {
"BACKEND": "storages.backends.s3boto3.S3Boto3Storage",
"OPTIONS": {
"location": "media", # Directory for media files
"file_overwrite": False, # Prevent overwriting files
},
},
"staticfiles": {
"BACKEND": "storages.backends.s3boto3.S3StaticStorage",
"OPTIONS": {
"location": "static", # Directory for static files
},
},
}
# Configuration during development
STATIC_URL = "/static/" # URL for static files
STATICFILES_DIRS = [BASE_DIR / "config" / "static"] # Directories for static files
STATIC_ROOT = BASE_DIR / "staticfiles" # Root directory for collected static files
MEDIA_URL = "/media/" # URL for media files
MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Root directory for media files
# S3 Configuration for production
if not DEBUG:
STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/"
MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/"
Использованная документация была взята с сайта https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html.
Я использую Django версии 5.1.4.
Хотя статические файлы (CSS, JS, активы) собираются корректно, при обращении к приложению верстка нарушается, не применяются стили и не загружаются изображения из папки static/assets.
Может ли кто-нибудь помочь мне решить эту проблему и убедиться, что статические файлы загружаются правильно в производственной среде?
Использованная документация была взята с сайта https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html.
Я использую Django версии 5.1.4.
Хотя статические файлы (CSS, JS, активы) собираются корректно, при обращении к приложению верстка нарушается, не применяются стили и не загружаются изображения из папки static/assets.
Может ли кто-нибудь помочь мне решить эту проблему и убедиться, что статические файлы загружаются правильно в производственной среде?
I managed to solve the issue, but I'll leave the question here with my solution in case someone encounters the same problem:
Steps for S3 Bucket Configuration:
Check the permissions of your bucket:
Disable all options in "Block public access" (bucket settings).
Add the following policy to your bucket (replace
your_bucket
with your actual bucket name):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your_bucket/media/*"
}
]
}
CORS (Cross-Origin Resource Sharing) Configuration: Add the CORS configuration to allow the necessary access:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"POST",
"PUT",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
Configuration in Django:
Here are the necessary settings to integrate S3 for storing media and serving static files through your server (like PythonAnywhere):
# Amazon S3 configuration for media
AWS_ACCESS_KEY_ID = "your_access_key_id"
AWS_SECRET_ACCESS_KEY = "your_secret_access_key"
AWS_STORAGE_BUCKET_NAME = "your_bucket"
AWS_S3_REGION_NAME = "your_region"
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_S3_QUERYSTRING_AUTH = False
# Storage configuration for S3 for media
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"
# Static and media directories
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [BASE_DIR / "config" / "static"] # Static files folder on the server
# In production, serve static files locally and media through S3
if not DEBUG:
STATIC_URL = "/static/"
MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/"
With these configurations, static files will be served by PythonAnywhere, while media files will be managed by Amazon S3.
My issue was caused by the AWS_S3_CUSTOM_DOMAIN
variable. Although I couldn’t pinpoint the exact error, I suspect it’s related to the SSL certificate. My suggestion is to avoid customizing the URL and leave that configuration to AWS, allowing it to manage the domain automatically.