William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Apache: Redirect http to https

I want to make a fake website: http://www.mytest.com/ to be accessed only through HTTPS protocol; or a certain dir with HTTPS access.
That means:

In order to implement this, there are 2 soultions and several pre-conditions are neccessary:


(1) There is a Linux server with root privilege to have the permission to setup environment.
(2) Have a SSL certification installed on the server.
(3) Have Apache server installed.
(4) Make sure the HTTPS (normally its port number is 443, which is defined at /etc/services) is configured.

The following codes are typically in httpd.conf, however, can be extending to other files if the following definition are in httpd.conf:

# Load config files from the config directory "/etc/httpd/conf.d".
Include conf.d/*.conf

Here I use other file inside conf.d/ to configure 443 port:

    ServerName www.mytest.com
    ServerAlias mytest.com
    DocumentRoot /home/mytest/
    SSLEngine on
    SSLCertificateinfo ...

After the above pre-setup done, we can do the implements.

Method 1: Redirect the Whole Website

Edit apache’s httpd.conf to append following line:

Redirect permanent / https://www.mytest.com/

By this way, any request made to http://www.mytest.com will goto https://www.mytest.com/

After the edit, restart Apache server:
# /etc/init.d/httpd restart
# ps -ef | grep httpd
to make sure the web server running normally.
Now it works. This is easiest way to ensure that your normal user never use plain text HTTP protocol to send data.

Method 2: use .htaccess to redirect the whole website, OR some certain dirs

We can redirect the whole website, or just some certain directories by defining .htaccess with mod_rewrite support.

In this way we need apache’s mod_rewrite module. Make sure it is active in httpd.conf:

LoadModule rewrite_module modules/mod_rewrite.so

After the installation, I create a .htaccess in my home directory:
/home/william$ vi ~/.htaccess:

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

Save the file, and goto web: http://mytest.com/~william. If the settins is correct, it will automatically redirect to https://mytest.com/~william.

A good reference is at: http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: