CloudFront与EC2重定向异常:需修改httpd.conf或EC2防火墙?
Hey there! Great to hear you've leveraged this community for help before, and thanks for flagging the specific redirect problem you're facing with CloudFront and EC2. Let's break this down clearly:
First off: this has nothing to do with EC2 firewall settings — firewalls control traffic access (like opening ports 80/443), they don't trigger URL redirects. The fix lies entirely in your httpd.conf (or related Apache configuration files like .htaccess).
Here's what you need to check and adjust in your Apache setup:
1. Set Correct ServerName and ServerAlias
Open your httpd.conf file (usually located at /etc/httpd/conf/httpd.conf or /etc/apache2/apache2.conf depending on your OS) and verify:
- The
ServerNamedirective is set to the custom domain you're using with CloudFront (e.g.,ServerName yourdomain.com), not your EC2 instance's hostname or public IP. - Add a
ServerAliasif you need to cover subdomains or alternate names (e.g.,ServerAlias www.yourdomain.com).
This tells Apache what domain it should "recognize" as its own, so it won't redirect to the underlying EC2 hostname.
2. Audit Redirect/Rewrite Rules
Look for any Redirect or RewriteRule directives in httpd.conf (or .htaccess files in your web root) that hardcode your EC2 instance's hostname or IP. For example:
- Bad:
RewriteRule ^(.*)$ http://ec2-12-34-56-78.compute-1.amazonaws.com$1 [R=301,L] - Good:
RewriteRule ^(.*)$ https://yourdomain.com$1 [R=301,L]
If you find any rules pointing to EC2's address, update them to use your CloudFront-associated domain instead.
3. Restart Apache and Test
After making changes:
- Restart the Apache service with
sudo systemctl restart httpd(usesudo systemctl restart apache2for Debian/Ubuntu systems). - Test the redirect behavior using
curl -I https://your-cloudfront-domain.com— check theLocationheader in the response. It should point to your custom domain, not the EC2 hostname/IP.
If you still run into issues, double-check that CloudFront is configured to pass the correct host header to your EC2 origin (in CloudFront's origin settings, ensure "Origin Custom Headers" includes the host header matching your domain). But 9 times out of 10, the root cause is Apache's own configuration.
内容的提问来源于stack exchange,提问作者Pramit J

