Redirect http to https with Apache mod_rewrite

Assuming you’re already loading the mod_rewrite module in Apache, you can add the following configuration to redirect traffic from http to https.

In your VirtualHost definition in httpd.conf:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

The same can also be accomplished in an .htaccess file, allowing for control at a directory level, provided the Directory definition has AllowOverride All. For example:

<Directory /var/www/>
AllowOverride All

Then add the Rewrite statements above in the file /var/www/

Either accomplish the same, but allow control at a different level of granularity.

Related link: Creating an SSL certificate for Apache

Creating an SSL certificate for Apache

Want https to work for your website? Here are the steps to create an SSL certificate to use with Apache.

Generate private key
$ openssl genrsa -out ca.key 2048

Generate CSR
$ openssl req -new -key ca.key -out ca.csr

With your CSR, you can send to a third-party to sign or self-sign. Self-signed certificates will produce warnings in browsers, so you may want to consider having a Certificate Authority sign your certificate.

Generate Self-Signed Key
$ openssl x509 -req -days 1095 -in ca.csr -signkey ca.key -out ca.crt

Move keys to where Apache will use them. This is the CentOS structure:
$ mv ca.crt /etc/pki/tls/certs/ca.crt
$ mv ca.key /etc/pki/tls/private/ca.key
$ mv ca.csr /etc/pki/tls/private/ca.csr

Secure these files with chown root and chmod 600. Permissions can be restrictive since Apache will read these in as root when starting.

Assuming you already have Apache set up for Virtual Hosts, you might have a config like this in your /etc/httpd/conf/httpd.conf:

NameVirtualHost *:443

<VirtualHost *:443>
ServerAlias *
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/ca.crt
SSLCertificateKeyFile /etc/pki/tls/private/ca.key
<Directory /var/www/>
AllowOverride All
DocumentRoot /var/www/
ErrorLog logs/
CustomLog logs/ common

Or better yet, for ease of maintenance, extract each Virtual host into its own config file (for example, /etc/httpd/conf/vhosts/ Next, add an include in your httpd.conf:

Include conf/vhosts/*.conf

Now restart Apache
$ apachectl restart

Good luck!

Related link: Redirect http to https with Apache mod_rewrite