How to serve files from S3 via CloudFlare

The docs that we can find on the cloudflare site are rather implicit and I had to google quite a lot to make it work. So here's my solution that may not be comprehensive but it may be good enough to get started.

1) Create a bucket called avatars.mywebsite.com

2) Add the following policy to it. Policy, not CORS.

{
    "Version": "2012-10-17",
    "Id": "http referer policy",
    "Statement": [
        {
            "Sid": "CloudFlare Requests",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::avatars.mywebsite.com/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "103.21.244.0/22",
                        "103.22.200.0/22",
                        "103.31.4.0/22",
                        "104.16.0.0/12",
                        "108.162.192.0/18",
                        "131.0.72.0/22",
                        "141.101.64.0/18",
                        "162.158.0.0/15",
                        "172.64.0.0/13",
                        "173.245.48.0/20",
                        "188.114.96.0/20",
                        "190.93.240.0/20",
                        "197.234.240.0/22",
                        "198.41.128.0/17"
                    ]
                }
            }
        }
    ]
}

What I believe it does is that it restricts the access to the bucket so that it could only be accessed with those IPs, which belong to CloudFlare and may be found somewhere on their website. Also I believe Id and Sid can contain any information that makes sense in your case.

3) Add a CNAME record in the CloudFlare DNS manager. Name should be avatars and value avatars.mywebsite.com.s3.amazonaws.com

4) Now, if you want to access a file in the bucket with a path like user/1/avatar.jpg from your website, use the following src:

https://avatars.mywebsite.com/user/1/avatar.jpg

5) It's worth pointing out that it may be required to change the SSL level from Full(Strict) to Full in the CloudFlare dashboard if HTTPS is used.