Tuesday 10 January 2017

Apache HTTP Server Rewrite Rules Basics

Apache Rewrite Rules Basics:

Note : Please note rewrite rules are evaluated first and then conditions staring from first condition. 

Syntax Example (301 Redirect of a a request to old host to new host):

RewriteCond %{REQUEST_URI} ^/hello1/hello2/*
RewriteCond %{HTTP_HOST} ^([a-z]{2})\.([a-z]+)\.xyz\.com
RewriteRule ^/(hello1)/(hello2)/* http://www.%2.xyz.com/$1/$2 [R=301,L]

# Note: 1 %n (where n could be any numeric from 1 to 9) is backreference notation which contains matched group value in the right hand side of the last RewriteCond part,in above example %2 is value of host which matches regex condition ([a-z]+)
#Note2 : $n (where n could be any numeric from 1 to 9) is backreference notation which contains matched group value in the left hand side of the RewriteRule part,in above example $1 is hello1 and $2 is hello2

List of Specific Characters Set in RewriteCond or RewriteRule :

RewriteCond %{REQUEST_URI} ^/(en|ca|it|fr)\-(us|ca|it|fr)/*
RewriteRule ^/(en|ca|it|fr)\-(us|ca|it|fr)/* http://www.xyz.$2 [R=301,L]

#Note: en-it or en-ca or any combination of above characters list will match the regex condition in RewriteCond and RewriteRule

White List of to allow a specific site access and block remaining:

RewriteCond %{HTTP_HOST} ^www\.xyz\.com
RewriteCond %{REMOTE_ADDR} !^aa.bb.cc.dd$
RewriteCond %{REMOTE_ADDR} !^aa1.bb1.cc1.dd1$
RewriteRule ^/* http://www.abc.com [R=301,L]

#Note: In above rewrite rule any request coming to host www.xyz.com will be redirected to host  http://www.abc.com unless requst is coming from above list public ip addresses aa.bb.cc.dd or aa1.bb1.cc1.dd1

URL Masking or Reverse Proxy:
Accessing a site xyz.com but internally it is serving content from internal site abc.com or in other way redirected to site abc.com however browser host url in will not be changed to abc.com. Example

RewriteCond %{HTTP_HOST} !^www\.xyz\.com
RewriteCond %{REQUEST_URI} ^/proxy$
RewriteRule ^(.*) http://www.abc.com$1 [P,L]

#Note: In above request url www.xyz.com/proxy will be internally redirected to site http://www.abc.com/proxy but in browser address bar we still see url www.xyz.com/proxy. Here config flag [P] is important as this flag is meant for proxy.

No comments:

Post a Comment

How to customize java.util.logging.Logger class to write logs in separate file than System.out.log in Websphere commerce/ HCL commerce)

/** * This method updated the passed in java.util.logging.Logger object with * custom file handler to write logs data form that class ...