简体   繁体   English

Django 使用 Aws S3 存储桶获取 static 文件

[英]Django using Aws S3 bucket to get static files

url.com/:9 GET https://<AWS_STORAGE_BUCKET_NAME>.s3.amazonaws.com/static/user/main.css net::ERR_ABORTED 403 (Forbidden)

url.com is the actual site and AWS_STORAGE_BUCKET_NAME is the bucket name url.com 是实际站点,AWS_STORAGE_BUCKET_NAME 是存储桶名称

When I try to retrieve my S3 file from my base.html I get a 403 forbidden error in the console.当我尝试从我的 base.html 检索我的 S3 文件时,我在控制台中收到 403 禁止错误。

<link rel="stylesheet" href="{% static 'user/main.css' %}" type="text/css">

Settings.py设置.py

# All of this is in my console.aws.amazon to configure aws s3 static files only
# IAM Management Console
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') 
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') 
# Amazon S3 Buckets
AWS_STORAGE_BUCKET_NAME =  os.environ.get('AWS_STORAGE_BUCKET_NAME') 
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'pages/static'),
]
STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
# For some reason I needed static root to collectstatistics
# STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

urls.py网址.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('pages.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
      
]
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": "arn:aws:s3::<bucket_name>/*"
        }
    ]
}

Adding that in Bucket policy in my AWS S3 permissions seemed to work.在我的 AWS S3 权限中的存储桶策略中添加它似乎有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM