Redirect http-requests to https

Submitted by matthiaslink on Sat, 2013-01-12 - 03:31

Challenge:
You want to make sure that anybody who access your home server has an SSL connection for
a) special pages
b) the complete site

A DNS record entry for e.g. set an alias from a fixed domain name to a dynamic DNS is protocol independent so you need a server side solution.

Solution:
To solve problem a) you may add a special .htaccess file to your web directory.

Assumption:
Apache module mod_rewrite must be active (e.g. check via phpinfo();)

Source of .htaccess in a folder that should be secured:

RewriteEngine On
RewriteCond %{SERVER_PORT}   !^443$
RewriteRule  (.*)  https://%{HTTP_HOST}/$1   [L]

For the problem b) you have to change your Apache config file. That small change allows to redirect any enquiries to port 80 (standard http port) to port 443 (standard https port). In combination with a CNAME record in your DNS domain you are able to relocate e.g. http://myserver.com to https://myserver.dyndns.com automatically.

Sourc of the apache config file; e.g. /etc/apache2/sites-available/default:


NameVirtualHost *:443
NameVirtualHost *:80

<virtualhost *:80>
        RewriteEngine On
        RewriteCond %{HTTPS} !=on
        RewriteRule ^/(.*) https://%{SERVER_NAME}%{REQUEST_URI} [R]
<virtualhost>

<virtualhost *:443>
        ServerName myserver.link-online.de
        ServerAdmin myemailaddy@link-online.de
        SSLEngine On
        SSLCertificateFile /etc/apache2/ssl/apache.pem
[...]
</virtualhost>

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.