Setting up a secure SSL sub-domain on Apache2

A detailed tutorial on how to set up a sub-domain on Apache2 that is served up on a secure SSL connection on port 443 using a self-signed certificate.

If you have part of your application that you would like to secure, you can use SSL1 encryption to encrypt the network connections between clients and your server. In this example, I will be hosting my main website on port 80, which will support unencrypted connections, and my mail sub-domain on port 443, which will be encrypted. Therefore the users of the mail system can be assured that their passwords and private emails will be sent through the Internet in a secure way.

Note that is this tutorial, I am using CentOS so the commands required might be slightly different on other platforms.

Using OpenSSL to generate a key and a cert

Begin by intalling mod_ssl for Apache2 and OpenSSL:

yum install mod_ssl
yum install openssl

Now using OpenSSL, generate a secure private key (substitute in your own hostname here):

openssl genrsa -out hostname.key 1024

Now generate a self-signed cert2, using the private key we just created:

openssl req -new -key hostname.key -x509 -out hostname.crt

You will now need to move these files into the directories used my mod_ssl:

mv hostname.crt /etc/pki/tls/certs/hostname.crt
mv hostname.key /etc/pki/tls/private/hostname.key

Configure mod_ssl to use these files:

nano /etc/httpd/conf.d/ssl.conf

...and change these settings to the following:

SSLCertificateFile /etc/pki/tls/certs/hostname.crt
SSLCertificateKeyFile /etc/pki/tls/private/hostname.key

Configure Apache2 to serve a sub-domain on port 443 only

To achieve this, we will set up a new virtual host declaration that will point to the foot folder where our mail application is installed. The user will access this using the sub-domain in their browser. If the user tries to access this sub-domain on HTTP (port 80), they will be re-directed to HTTPS (port 443) using mod_rewrite3. Here is the new configuration required:

nano /etc/httpd/conf/httpd.conf


NameVirtualHost *:443
<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/hostname.crt
    SSLCertificateKeyFile /etc/pki/tls/private/hostname.key
    <Directory /var/www/mailapp>
            AllowOverride All
    DocumentRoot /var/www/mailapp

And to force all port 80 traffic on this sub-domain to redirect to port 443, add:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(mail)\. [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]


John Collins

I have been writing about web technology and software development since 2001. I am the developer of the Alpha Framework for PHP, and the personal productivity app. I love open source, technology, and economics.