Skip to content

Latest commit

 

History

History
59 lines (42 loc) · 2.33 KB

2024-05-27-serve-media-files-from-s3-bucket-through-cloudfront.md

File metadata and controls

59 lines (42 loc) · 2.33 KB
tags
django
AWS

Set up Cloudfront as a CDN to serve media files

Previously I wrote about how to set up media file upload for a Django application to S3 Bucket. Serving them from the s3 bucket directly would also be feasible, if your website does not have a lot of traffic, and the visitors of your website are close to the geographic region of your S3 bucket. The advantage is that you have less complexity for the set-up.

But in case one of the two criteria mentioned are not fulfilled, you should consider using Cloudfront or a similar service such as Cloudflare R2 to serve your media files. Some advantages are:

  • Faster response times
  • DDoS protection
  • Scalability

The good news is that "django-storages" makes the configuration in your Django application easy. The bad news is that AWS is notoriously complex and the most work needs to be done in the console. Or maybe it can be done with the aws-cli, and I might make a follow-up post in the future.

Set up Cloudfront with S3 Bucket

I created a Cloudfront distribution, selected the S3 Bucket as the Origin Domain Name and set the Cache policy "CachingOptimized" (suggested for S3 Buckets)

img.png

After that, you can copy the cloudfront domain for your created distribution, and save it in the app settings, for example:

CLOUDFRONT_DOMAIN = "d3268ld43vues4.cloudfront.net"

Next, I configured the Origin Access Control for the S3 Bucket, since the S3 Bucket I created is not publicly active.

img_1.png

Here, I created a new OAC, and copied the policy, which looked like this:

img_2.png

I had to add this policy to my S3 Bucket and update the "django-storages" setting:

STORAGES = {
    "default": {
        "BACKEND": "storages.backends.s3.S3Storage",
        "OPTIONS": {
            "bucket_name": AWS_STORAGE_BUCKET_NAME,
            "file_overwrite": False,
            "custom_domain": CLOUDFRONT_DOMAIN,
        },
    }
}

Now the url generated by Django's ImageFiled was pointing to Cloudfront and the path of the image inside the S3 Bucket.