Search code examples
djangoamazon-s3django-staticfiles

Serving static files from private s3 in django


Is there a way to serve static files from private s3. i know there are plenty of tutorials (like https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html) that help u in serving static files from public buckets.

i serve my media files. and i get a signed url which will timeout after 120s. can i not get a similar url for static files?

i am sorry if this sounds stupid.

STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'),]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

DEFAULT_FILE_STORAGE ='storages.backends.s3boto3.S3Boto3Storage'

AWS_ACCESS_KEY_ID = "***************"

AWS_SECRET_ACCESS_KEY ="**********"

AWS_STORAGE_BUCKET_NAME = "*********"

AWS_S3_REGION_NAME = 'us-east-2'

AWS_S3_SIGNATURE_VERSION = 's3v4'

AWS_DEFAULT_ACL = None

AWS_QUERYSTRING_EXPIRE = 120

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

AWS_LOCATION = 'static'

STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)

STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

this is my settings.py and

my media files... i get a signed url when i query it.... but my static files ... i dont get a signed url (i.e. it looks like https://bucketname.s3.us-east-2.amazonaws.com/Path/file_fileext/)

so i get a 403 forbidden

note:

my bucket iam user has AmazonS3FullAccess permission

my bucket policy is EMPTY

my block all public access is ON

AND

this is my cors policy

[

{

"AllowedHeaders": [

"*"

],

"AllowedMethods": [

"GET",

"HEAD",

"POST",

"PUT",

"DELETE"

],

"AllowedOrigins": [

"*"

],

"ExposeHeaders": [],

"MaxAgeSeconds": 3000

}

]

Solution

  • So, finally, I was able to do it and since there weren't many resources on this topic, decided to write a post on my medium. Here's the link: https://shrinidhinhegde.medium.com/how-to-serve-django-static-files-in-a-production-environment-from-a-private-s3-bucket-using-aee840a5a643