Home > Blockchain >  Django using Aws S3 bucket to get static files
Django using Aws S3 bucket to get static files

Time:12-20

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

When I try to retrieve my S3 file from my base.html I get a 403 forbidden error in the console.

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

Settings.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

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')),
      
]

CodePudding user response:

{
    "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.

  • Related