Sunday, January 27, 2013

How to use mod_rewrite to redirect the request to your web application?

Recently, I was asked to redirect those request that direct access to the root of my web server(for example, http://[SERVER]/ or http://[SERVER]/index.html or https://[SERVER]/ or https://[SERVER]/index.html) to the login page of my web application. Due to some reason, I just can't use RedirectMatch or Redirect, I have more RewriteRule which I need to take into consideration. Below are some simple configuration by using RewriteEngine to achieve the requirement.

First step, open https.conf and comment out

LoadModule rewrite_module modules/

For your info, I have configured 2 virtual host in httpd-vhosts.conf

1. 1 virtual host which is listening to port 80
2. 1 virtual host which  is listening to port 443, which is my SSL configuration.

I also configured mod_jk redirect traffic request to my Apache Web Application Server which is in my virtual host configuration as well.

Hence, my httpd-vhost.conf is currently having configuration like this,

<VirtualHost *:80>     ServerAdmin
     DocumentRoot "C:\Apache24\htdocs"
     ErrorLog "logs/"
     CustomLog "logs/" common

<VirtualHost *:443>
     ServerAdmin     DocumentRoot "C:\Apache24\htdocs"
     ErrorLog "logs/"
     CustomLog "logs/" common

I add the rewrite rule to each of the virtual host configuration

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/index.html [OR]
RewriteCond %{REQUEST_URI} "^/$"
RewriteRule (.*)  https://%{HTTP_HOST}/myapp/ [R=301,L]

This is to make sure, whoever open the browser and type in
 http://[SERVER]/ or http://[SERVER]/index.html or https://[SERVER]/ or https://[SERVER]/index.html will be getting redirect to https://[SERVER]/myapp/ which is the URL of my web application.

1 comment:

Mike said...

Well written information on how to use mod_rewrite to redirect the request to your web application. I will surely try it and hope that it will work great for me.
digital signature