Want to redirect requests for http://www.yoursite.com to https://www.yoursite.com?
There are many suggestions out there to add a .htaccess file with rewrite conditions[1] but I figured I’d suggest a second, through a simple change to your httpd.conf file (or if you are running Ubuntu or another distro that splits the httpd.conf file into multiple files, in your /etc/apache2/sites-available/{yoursite} configuration file. (If you are running a pretty Ubuntu install, the file is /etc/apache2/sites-available/default)
This technique still uses the rewrite engine (so you’ll need mod_rewrite module) but it places the configuration in the httpd.conf file (or its equivalent) and out of the .htaccess file. There are many reasons you might want to do this, such as prevent it from being changed (many site configurations allow users to edit all .htaccess files but prevent them from editing the httpd.conf file) or to prevent it from being overwritten by certain web application packages (many application packages including WordPress and MediaWiki employ custom .htaccess files to provide more friendly URLs).
The change is simple, in your httpd.conf file, change the following part of your virtual host section:
<VirtualHost *:80>
ServerAdmin contact@yourwebsite.com
DocumentRoot /var/www/public
<Directory />
… to something resembling the following:
<VirtualHost *:80>
RewriteEngine on
ReWriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
</VirtualHost>
<VirtualHost *:443>
ServerAdmin contact@yourwebsite.com
DocumentRoot /var/www/public
SSLEngine On
SSLCertificateFile /etc/apache2/ssl/mycert.pem
SSLCertificateKeyFile /etc/apache2/ssl/mycert.key
<Directory />
The important things here are that the port 80 Virtual Host has been changed to listen on port 443 (Line 7), there is a new Virtual Host that has been added above our existing Virtual Host that is set to listen on port 80 and only contains the rewrite code (Lines 1-5), and finally, there are lines added that enable and configure the SSLEngine (settings may differ based on implementation)(Lines 12-14).
Restart Apache and your browser should redirect requests to http://www.yoursite.com/ to https://www.yoursite.com. In case you’re wondering, a request for http://www.yoursite.com/staff/about.php will also redirect to https://www.yoursite.com/staff/about.php.
RSS Feed