Reputation: 359
I'm using an Amazon S3 bucket named images.example.com which successfully serves content through Cloudflare CDN using URLs like:
https://images.example.com/myfile.jpg
I would like to prevent hotlinking to images and other content buy limiting access to only the referring domain: example.com and possibly another domain which I use as a development server.
I've tried a bucket policy which both allows from specific domains and denies from any domains NOT the specific domains:
{
"Version": "2012-10-17",
"Id": "http referer policy example",
"Statement": [
{
"Sid": "Allow get requests referred by www.example.com",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::images.example.com/*",
"Condition": {
"StringLike": {
"aws:Referer": [
"http://www.example.com/*",
"http://example.com/*"
]
}
}
},
{
"Sid": "Explicit deny to ensure requests are allowed only from specific referer.",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": "arn:aws:s3:::images.example.com/*",
"Condition": {
"StringNotLike": {
"aws:Referer": [
"http://www.example.com/*",
"http://example.com/*"
]
}
}
}
]
}
To test this. I uploaded a small webpage on a different server: www.notExample.com where I attempted to hotlink the image using:
<img src="https://images.example.com/myfile.jpg">
but the hotlinked image appears regardless.
I've also attempted the following CORS rule
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>http://www.example.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Neither of these has worked to prevent hotlinking. I've tried purging the cached files in CloudFlare, using combinations of bucket policy and CORS (one or the other plus both) and nothing works.
This seems to be a relatively simple thing to want to do. What Am I doing wrong?
Upvotes: 2
Views: 2156
Reputation: 269101
Cloudflare is a Content Distribution Network that caches information closer to end users.
When a user accesses content via Cloudflare, the content will be served out of Cloudflare's cache. If the content is not in the cache, Cloudflare will retrieve the content, store it in the cache and serve it back to the original request.
Your Amazon S3 bucket policy will therefore not work with Cloudflare, since the page request is either coming from Cloudflare (not the user's browser that generates a Referrer), or being served directly from Cloudflare's cache (so the request never reaches S3).
You would need to configure Cloudflare with your referrer rules, rather than S3.
See: What does enabling CloudFlare Hotlink Protection do?
Some alternatives:
referer
rules. Amazon S3 also supports pre-signed URLs that your application can generate.Upvotes: 5