S3托管网站向EC2发送HTTP请求的安全组配置方案
Great question! Let's break this down clearly because there's a key detail about how S3-hosted static websites work that changes everything here.
First, a critical clarification: When users visit your S3 static site, their browsers load static content directly from S3. Any HTTP requests your frontend sends to EC2 come from the user's browser IP address—not from S3 itself. That's why you can't just add S3's IP ranges to your EC2 security group and call it done; those backend requests never originate from S3 servers.
Why S3 IP ranges aren't the solution
S3 uses a massive, dynamic set of IP addresses across all AWS regions. Even if you managed to add every S3 IP to your security group, you'd be opening EC2 up to any user who interacts with S3 (not just your website's visitors)—which is way too broad and defeats the purpose of restricting access.
Practical, secure alternatives
Here are the most reliable ways to lock down your EC2 backend to only legitimate traffic from your S3 frontend:
1. Route traffic through CloudFront
- Set up CloudFront to serve your S3 static website (this also boosts performance and adds DDoS protection).
- Update your EC2 security group to allow incoming HTTP/HTTPS traffic only from CloudFront's edge node IP ranges. AWS provides a managed prefix list (
com.amazonaws.global.cloudfront.origin-facing) you can directly reference in your security group—this list auto-updates as CloudFront's IPs change, so you don't have to manually maintain IP lists. - For extra security, use an Origin Access Identity (OAI) to ensure S3 only serves content to CloudFront, blocking direct public access to your bucket.
2. Use API Gateway as an intermediary
- Create an API Gateway endpoint that forwards requests to your EC2 instance.
- Configure your EC2 security group to only accept traffic from API Gateway's IP ranges, or use a VPC Link if your EC2 is in a private VPC (this keeps traffic entirely within AWS's network).
- API Gateway also lets you add authentication layers (like API keys, OAuth, or JWT) to ensure only valid requests from your frontend get through.
3. Add token-based authentication to your frontend
- Implement JWT or similar token auth in your S3-hosted frontend. Have users obtain a valid token from an auth service (like AWS Cognito) before sending requests to EC2.
- Set up your EC2 instance to validate these tokens on every incoming request. Even if random IPs try to access EC2, they won't have a valid token and will be rejected. You can pair this with security group rules that restrict traffic to common client IP ranges for an extra layer of safety.
Final takeaway
The core issue is that S3 doesn't proxy requests to your EC2—your users' browsers do. To secure EC2, you need to either route traffic through an AWS service with controllable IP ranges (CloudFront/API Gateway) or add authentication to verify each request's legitimacy.
内容的提问来源于stack exchange,提问作者rodrigocf

