为Amazon CloudFront添加Referer校验:源站头部处理咨询
Hey there! I get that you've already added the Referer header to your whitelist, but you're wondering how to handle it on the origin server side—let's break this down clearly for you.
一、核心处理逻辑
First off, the origin server's main job here is to validate whether the incoming request's Referer header falls within your allowed list (like your https://example.com/ domain). This helps prevent hotlinking or unauthorized requests from external sites.
二、头部名称与值的正确设置
Let's clear up the basics first:
- Header Name: It's critical to use
Referer(note the single "r"—this is the standard HTTP spelling, not "Referrer" which is a common typo). HTTP headers are case-insensitive, but sticking to the standard avoids unexpected issues. - Header Value: This is the full URL of the page that initiated the request. For example, if a user clicks a link on
https://example.com/blog/post, the Referer value sent to your origin will be that full URL. If someone directly enters your resource URL in the address bar, the Referer might be empty or missing entirely.
三、源站配置:Simple is often best
The https://example.com/ * pattern you mentioned works, but the exact syntax depends on what server or tool you're using for your origin. Here are common examples:
For Nginx users
Use the valid_referers directive to define allowed sources:
valid_referers none blocked https://example.com/ https://example.com/*; if ($invalid_referer) { return 403; # Block requests with invalid Referers }
none: Allows requests with no Referer header (direct visits, privacy-focused browsers)blocked: Allows requests where the Referer was modified/removed by a proxy/firewallhttps://example.com/&https://example.com/*: Matches all pages under your domain
For Apache users
Leverage mod_rewrite to filter requests:
RewriteEngine On # Allow requests with no Referer (direct visits) RewriteCond %{HTTP_REFERER} !^$ # Block requests from non-allowed domains RewriteCond %{HTTP_REFERER} !^https://example.com/.*$ [NC] RewriteRule ^.*$ - [F,L] # Return 403 Forbidden
- The
[NC]flag makes the match case-insensitive, so it works for variations likeHTTPS://EXAMPLE.COM/
Key takeaway
You don't need overcomplicated rules. Just define your allowed domain(s) explicitly, and make sure to account for edge cases like missing Referers—otherwise you might block legitimate users with privacy settings enabled.
四、Quick testing tip
After setting up, verify with curl to make sure it works as expected:
# Test a valid Referer request (should return 200 OK) curl -H "Referer: https://example.com/test-page" https://your-origin-domain.com/your-resource # Test an invalid Referer request (should return 403 Forbidden) curl -H "Referer: https://random-external-site.com/" https://your-origin-domain.com/your-resource
内容的提问来源于stack exchange,提问作者user2528676

