Sunday, August 7, 2011

Redirecting a URL to a different port with and without conditions

Redirecting a URL and using a specific port is a question that got my head scratching one day. Someone had a login
page for example login.html. To enhance security they later decided they would set up another server that listened on
a nonstandard port (8080) and move the login page to there. To implement this they needed to employ URL and port
redirection. This is how the port redirection can be done:

--------------------------------------------------------------------------------------------------------
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[a-z]{3,9}\ /login\.html\ HTTP/ [NC]
RewriteRule ^.*login\.html$ http://secure1.example.com:8080/ [R=301,L]
--------------------------------------------------------------------------------------------------------
For use in .htaccess and if it is not set globally or for the root directory of your domain, be sure to set
Options +Indexes +FollowSymLinks as needed before the RewriteEngine On directive.
Also, depending on your server configuration you may need to use RewriteBase. Typical usage is RewriteBase /
placed just after the RewriteEngine On directive. Further details on RewriteBase are provided in a previous section.

This example is very similar to the How to redirect your home page example above except here RewriteRule and
RewriteCond match \login.html. Note that the RewriteCond insures that the target of the GET is for login.html from
only the root directory of the domain. If such a strict interpretation is not required you can remove the RewriteCond
statement. The port redirection itself is specified by the :8080 in the second argument to RewriteRule.

TIP!
You can even get more creative by modifying the RewriteCond to use HTTP_USER_AGENT in place of THE_REQUEST,
use negation on the second argument and then specify the regex for say msnbot,Slurp or Googlebot. This would cause
redirection to occur except if a search bot was requesting. This is useful because bots can't login so this would
be a method to provide crawalable content that otherwise would not get indexed.

No comments:

Post a Comment