在AWS EC2 Ubuntu16 LTS服务器上设置页面默认加载HTTPS
Hey there! Since you've already wrapped up the SSL setup and got your config files in place, let's walk through getting your site to load over HTTPS by default (with automatic redirects from HTTP). Here's what you need to do:
Step 1: Enable Apache's Rewrite Module
First, make sure the rewrite module is enabled—this is what lets us create the HTTP-to-HTTPS redirect rule. Run these commands:
sudo a2enmod rewrite sudo systemctl restart apache2
Step 2: Add HTTP-to-HTTPS Redirect Rules
Since you created /etc/apache2/httpd.conf (instead of using the default 000-default.conf), we'll add the redirect logic directly here. Open the file with your preferred editor (like nano):
sudo nano /etc/apache2/httpd.conf
Paste in the following virtual host block for port 80 (HTTP):
<VirtualHost *:80> # Enable rewrite engine RewriteEngine On # Redirect all HTTP traffic to HTTPS permanently RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </VirtualHost>
The R=301 flag means this is a permanent redirect, which is best for SEO and ensures browsers cache the redirect for future visits.
Step 3: Ensure Your HTTPS Virtual Host is Enabled
Chances are you have an SSL config file in /etc/apache2/sites-available/ (like default-ssl.conf from your earlier setup). Let's make sure it's enabled so Apache uses it for HTTPS traffic:
sudo a2ensite default-ssl.conf
Step 4: Verify Apache Configuration & Restart
Before restarting, check for any syntax errors in your configs—this saves you from unexpected downtime:
sudo apache2ctl configtest
If you see Syntax OK, go ahead and restart Apache to apply all changes:
sudo systemctl restart apache2
Step 5: Test the Redirect
Open your browser and visit http://your-domain-or-ec2-ip—you should automatically be redirected to https://your-domain-or-ec2-ip. If not, double-check your AWS security group allows both port 80 (HTTP) and 443 (HTTPS) inbound traffic.
Quick Check: Is httpd.conf Being Loaded?
Ubuntu's Apache setup usually pulls configs from the sites-enabled directory by default, so make sure your httpd.conf is being included in the main Apache config. Open /etc/apache2/apache2.conf and add this line if it's missing:
Include /etc/apache2/httpd.conf
Save the file and restart Apache again if you made this change.
内容的提问来源于stack exchange,提问作者OtagoHarbour

