November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Categories

November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Mod_rewrite

Turn Mod_Rewrite On

Mod_rewrite is used through your .htaccess file. Place the following code at the beginning of your .htaccess file to turn mod_rewrite on:

RewriteEngine on

(Don’t forget that .htaccess commands are case-sensitive.) This code needs to be entered at the beginning of any .htaccess file using mod_rewrite.
The Basic Mod_Rewrite Layout

The basic format for a mod_rewrite command is:

RewriteRule Pattern Substitution [Flag(s)]

URLs are Always Relative

The URL you redirect to is always relative to the directory in which your .htaccess file is placed.
So if it’s in the root directory, URLs are all in relation to the root directory; if it’s in a sudirectory, URLs are in relation to that particular subdirectory.
A Basic Redirect

If you just want to create a simple 301 redirect from one URL to another, then use the following code:

RewriteRule ^fileone.html$ filetwo.html

This is a very basic rule that means any requests for fileone.html will be sent to filetwo.html.
Require no “www”

This bit of code will make it so visitors to your site don’t need to type in the “www” bit of your website address.
view plaincopy to clipboardprint?

RewriteCond %{HTTP_HOST} !^rmohan\.com$ [NC]
RewriteRule ^(.*)$ http://rmohan.com/$1 [R=301,L]

Block a Specific IP Address

If you want to block someone coming from a specific IP address from accessing your website, you can use the following code:
view plaincopy to clipboardprint?

RewriteCond %{REMOTE_ADDR} ^(A\.B\.C\.D)$
RewriteRule ^/* http://www.rmohan.com/sorry.html [L]

Replace the A\.B\.C\.D with the IP address you want to block (don’t forget to leave the “\” before each dot, which escapes the character).
Block Specific User Agents

If you want to block a group of IP addresses using the same User Agent (bot), the following code with do it:

RewriteCond %{HTTP_USER_AGENT} UserAgent
RewriteRule .* – [F,L]

Just replace the “UserAgent” bit with whatever user agent you want to block. You can also block more than one at a time by replacing the top line in that code with something like this:

RewriteCond %{HTTP_USER_AGENT} UserAgentA [OR]
RewriteCond %{HTTP_USER_AGENT} UserAgentB

You can put as many user agents in as you want, just make sure you end each line with [OR] (with the exception of the last line, of course).

Let’s say all the pages on your site other than your home page are formatted as follows, with query strings instead of page names:

http://www.rmohan.com/home.html?rmohan=12345abcd

Those aren’t very pretty, and on top of that, search engines will show a bunch of duplicated “home” pages. If you want to get rid of the query string in your page URLs, use the following code:
view plaincopy to clipboardprint?

RewriteCond %{QUERY_STRING} rmohan=
RewriteRule (.*) http://www.rmohan.com/$1? [R=301]

This not only gets rid of the query string, but also the preceding question mark.
Set up a Default Image

Using a default, backup image in case of broken images can make your site look more professional.
Use the following code to redirect to a default image for any image whose file cannot be found.
view plaincopy to clipboardprint?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/.*\.jpg$ /images/default.jpg [L]

Of course, you can change the “.jpg” bit to whatever file type you’re using.
Make sure you have an image called “default.jpg” or change that to whatever your default image filename is.

Prevent Hotlinking

The last thing most website owners want is other sites stealing their content or worse—hotlinking to their images and stealing their bandwidth.
Here’s a simple bit of code that prevents it:
view plaincopy to clipboardprint?

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?rmohan.com/ .*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

Redirect to a Maintenance Page

If you need to take your entire site offline for a bit and redirect to a maintenance page (or some other page), use the following code:

RedirectMatch 302 ^/ /maintenancepage.html

Change the “maintenancepage.html” bit to wherever your maintenance page file is located.
Redirect Multiple rmohans to a Single rmohan

If you have multiple rmohans pointing to your site, it’s possible you could take a hit in the search engines for having duplicate content.
Use the following code to redirect visitors from two rmohans to just one:
view plaincopy to clipboardprint?

RewriteCond %{HTTP_HOST} ^www.rmohan.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^rmohan.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.rmohan.com$ [NC]
RewriteRule ^(.*)$ http://rmohan.com/$1 [R=301,L]

Remember the Filesystem Always Takes Precedence

The filesystem on your server will always take precedence over the rewritten URL. For rmohan, if you have a directory named “services” and within that directory is a file called “design.html”, you can’t have the URL redirect to “http://rmohan.com/services”. What happens is that Apache goes into the “services” directory and doesn’t see the rewrite instructions.

To fix this, simply rename your directory (adding an underscore to the beginning or end is a simple way to do that).

check it yourself using these simple step.

Step1. Create a blank text file using notepad or any other editor.
Step2. Put <?php phpinfo(); ?> in the file.
Step3. Save as ‘info.php’ [on windows Save as “info.php” (with double quotes)].
Step4. Upload the file to your web server’s root or any other folder.
Step5. Call the file in the url – http://your-rmohan.com/info.php and check if you see mod_rewrite in ‘Apache loaded modules’ section.
If NOT, then please contact your hosting provider and request them to install/enable mod_rewrite.

Note: If you have access to your httpd.conf file, you may check for mod_rewrite in that file as well. And also your httpd.conf must be configured to allow Fileinfo override. Contact your hosting provider for any server related issues.

Next thing you would do is check your .htaccess file. Make a backup of your existing .htaccess file so that in case because of your changes if web server does not serve your site, you can always restore the backup copy.
rmohans of mod_rewrite

1. Description – Your current pages are called using index.php with parameter of url i.e
http://www.rmohan.com/index.php?url=category
and instead of this URL, you want a nice and easy to read URL like http://www.rmohan.com/category
Solution – Put the following lines in your .htaccess file.

RewriteEngine on
RewriteRule ^([^/\.]+)/?$ /index.php?url=$1 [L]

Note: If your file already contains a line ‘RewriteEngine on’ then you don’t need to put it again unless it was set to off before you putting in your lines.

2. Description – Your current URL is
http://www.rmohan.com/index.php?cat=category&subcat=subcategory
which you would like to see as
http://www.rmohan.com/category/subcategory
Solution – Put the below lines in your .htaccess file

RewriteEngine on
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /index.php?cat=$1&subcat=$2 [L]

3. Description – You want to have many sub categories or categories like
http://www.rmohan.com/category/subcat1/subcat2/subcat3/subcat4/subcat5/
which you would to rewrite to
http://www.rmohan.com/index.php?cat=category&subcat1=subcat1&subcat2=subcat2 and so on …
Solution – See below lines..

rmohan.com/category –> index.php?cat=category
RewriteRule ^([^/\.]+)/?$ /index.php?cat=$1 [L]

rmohan.com/category/subcategory/ –> index.php?cat=category&subcat=subcategory
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /index.php?cat=$1&subcat=$2 [L]

rmohan.com/p1/p2/p3/ –> index.php?a=p1&b=p2&c=p3
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /index.php?a=$1&b=$2&c=$3 [L]

rmohan.com/p1/p2/p3/p4 –> index.php?a=p1&b=p2&c=p3&d=p4
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /index.php?a=$1&b=$2&c=$3&d=$4 [L]

4. Description – Your URL has a folder and you would like rewriting for that folder. The URL looks like this http://rmohan.com/folder/index.php?url=name which you want to see as http://rmohan.com/folder/name/
Solution – Place the following lines in your .htaccess file

RewriteEngine on
RewriteRule ^folder/([^/\.]+)/?$ folder/index.php?url=$1 [L]

5. Description – Your actual URL is http://rmohan.com/index.php?page=hello which you want to see as http://rmohan.com/hello.htm
Solution – Place the following lines in your .htaccess file

RewriteEngine on
RewriteRule ^([^/\.]+).htm$ index.php?page=$1 [L]

6. Description – Your URL is http://rmohan.com/folder/index.php?page=hello which you want to see as http://rmohan.com/folder/hello.htm
Solution – Place the following lines in your .htaccess file

RewriteEngine on
RewriteRule ^folder/([^/\.]+).htm$ folder/index.php?page=$1 [L]

Force redirect the NON www version to www. version by HTACCESS

ou want to force the www in your domain name (and you don’t have subdomains), as for example our website is http://rmohan.com and we want our visitors when type http://rmohan.com in their browsers address bar they will be redirected to http://www.rmohan.com ( www. added to URL).

You will need Apache’s {HTTP_HOST} variable to see if the www. is already there and, if not, redirect.

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.rmohan\.com$ [NC]
RewriteRule .? http://www.rmohan.com%{REQUEST_URI} [R=301,L]

Explanation :
{HTTP_HOST} is the Apache variable, which always starts with %.

The RewriteCond %{HTTP_HOST} !^www\.rmohan\.com$ [NC] means when the HTTP_HOST or domain name typed is not www.rmohan.com then a redirection happens by the following statement.
RewriteRule .? http://www.rmohan.com%{REQUEST_URI} [R=301,L]

%{HTTP_HOST} !^www\.rmohan\.com$ [NC] means
%{HTTP_HOST} NOT (!) STARTS WITH (^) www.rmohan.com ENDS WITH ($)
that is %{HTTP_HOST} not equal to www.rmohan.com or that means %{HTTP_HOST} doesnot match with www\.rmohan\.com

Here \ is an ESCAPE CHARACTER, . is used by HTACCESS and have a regular expression meaning, so when you need to use . in a regular expr statement you need to write \ before it as \., e.g thanks. should be written as thanks\.

NC means NO CASE, that is uppercase or lowercase letters doesnot matter. This is because domain name is not case sensitive.

Now the RewriteRule statement in HTACCESS
RewriteRule .? http://www.rmohan.com%{REQUEST_URI} [R=301,L]

The RewriteRule says to match zero or one of anything then redirect to http://www.example.com with the original {REQUEST_URI}. The R=301 tells the browser (and search engines) that this is a permanent redirection and the Last flag tells mod_rewrite that you’ve completed your redirection.

 

For example normal website name is http://www.rmohan.com, and you want to redirect all mobile visitors based on mobile devices then add below code in your .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]
RewriteRule .* http://www.rmohan.com/ [R]

Note: Replace www.rmohan.com with your domain name.

The htaccess code works by examining a special string, called HTTP header “User-Agent” which the browser send. For exampe iPad sends a User-Agent header similar to this one

User-Agent: Mozilla/5.0 (iPad; U; CPU OS 4_3_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8G4 Safari/6531.21.10

What if we want to redirect users to mobile site and in the same time give them an ability to switch back to the full site version. then add below rules to .htaccess file.

// This code for redirecting user to the mobile site unless there is a cookie //
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]
RewriteCond %{HTTP_COOKIE} !^.*mobilesite=no.*$
RewriteRule ^.*$ https://m.rmohan.com [R=301]

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]
RewriteCond %{HTTP_COOKIE} !^.*mobilesite.*$
RewriteRule ^.*$ https://m.rmohan.com [R=301,CO=mobilesite:yes:.rmohan.com:60]

In the above rule cookie expiration time is set to 60 minutes, during this time user will access non mobile site version. Please don’t forget to replace domain names.

But what if user is requested a non-mobile site, then add below rules to give full version of website.

RewriteEngine On
RewriteCond %{REQUEST_URI} ^.*fullversion.*$
RewriteRule ^.*$ https://rmohan.com [R,L,CO=mobilesite:no:.rmohan.com:60]

 

Manipulating the Query String in Apache Rewrite

 

The query string is the part of the URL that follows the question mark (?). It is often used to pass parameters to CGI scripts or other dynamic pages. It is typically available in the QUERY_STRING environment variable.

The typical URL-manipulation directives such as , Redirect, Alias, and RewriteRule cannot directly access the query string. But mod_rewrite can be used to add, remove, or modify the query string. The trick is to use a RewriteCond to match against the %{QUERY_STRING} variable and, if necessary, the [QSA] flag to append to an existing query string.

Some examples follow. These examples all assume that they are placed in the main server configuration file. If they are placed in a section or .htaccess file, the RewriteRule will need to be modified accordingly. Also, these examples can all be transformed from internal alias to external redirects by adding the [R] flag to the RewriteRule.

Be cautious when dealing with complex query strings, since the order of the variables is often arbitrary.

 

Access control by Query String

Deny access to http://example.com/page?var=val if var=val contains the string foo.

 

RewriteCond %{QUERY_STRING} foo
RewriteRule ^/page - [F]

 

Removing the Query String

Delete the query string entirely.

 

RewriteRule ^/page /page?

 

Adding to the Query String

Keep the existing query string using the Query String Append flag, but add var=val to the end.

 

RewriteRule ^/page /page?var=val [QSA]

 

Rewriting For Certain Query Strings

Rewrite URLs like http://example.com/page1?var=val to http://example.com/page2?var=val but don’t rewrite if val isn’t present.

 

RewriteCond %{QUERY_STRING} val
RewriteRule ^/page1 /page2

Note that you don’t need to use the Query String Append flag if you won’t modify the query string in the RewriteRule; it is left as-is in the URL by default.

 

Modifying the Query String

Change any single instance of val in the query string to other_val when accessing /path. Note that %1 and %2 are back-references to the matched part of the regular expression in the previous RewriteCond.

 

RewriteCond %{QUERY_STRING} ^(.*)val(.*)$
RewriteRule /path /path?%1other_val%2

 

Making the Query String Part of the Path

Take a URL of the form http://example.com/path?var=val and transform it into http://example.com/path/var/val. Note that this particular example will work only for a single var=val pair containing only letters, numbers, and the underscore character.

 

RewriteCond %{QUERY_STRING} ^(\w+)=(\w+)$
RewriteRule ^/path /path/%1/%2?

 

Making the Path Part of the Query String

Essentially the reverse of the above recipe. But this example, on the other hand, will work for any valid three level URL. http://example.com/path/var/val will be transformed into http://example.com/path?var=val.

 

RewriteRule ^/path/([^/]+)/([^/]+) /path?$1=$2

These days, on-line services. Blog and wiki services also need to port 80, so 80 to Apache management, then 8080 Tomcat behind apache connection.

The main Apache + Tomcat There are three ways: mod_jk, mod_proxy and ajp_proxy. mod_jk more specific method of Tomcat through AJP protocol connection Tomcat, mod_proxy is more than can be connected to the Tomcat, as long as the application HTTP reverse proxy. ajp_proxy not very clear, specific, see here.

I encountered three different configurations before and after. First build a test service, service structures on one machine within the network and outside the network machine’s 8080 port mapping network port 80 access. Port due to external exposure only be mapped to a 80-port, natural Apache push up. Using mod_proxy reverse proxy configuration. Then the above requirements to build two running instances, he opened it the two Tomcat, with a duplicate proxy. One in 18,080, one at 28080.
? View Code CONF

ProxyPass / app http://localhost:18080/app
ProxyPassReverse / app http://localhost:18080/app
ProxyPass / app2 http://localhost:28080/app2
ProxyPassReverse / app2 http://localhost:28080/app2

The second environment is not Apache + Tomcat, but IIS + Tomcat. Not familiar with IIS, within a period of time scratching their head. IIS, I did not find practical mod_proxy components, in particular the use of the ISAPI mod_proxy. Another major change in demand, this request for service support SaaS our service SaaS domain name to distinguish the different tenants. Users such as visit through abc.example.com and def.example.com, although the use of the same application, but to operate in a different tenant space.
Possible solution is to use the ISAPI Rewrite. The ISAPI Rewrite fact Proxy functionality, but that is fee-based version. The free Lite version only URL Rewrite function. I had to completely give up the intention of the proxy, redirect the user to do. Such as access http://abc.example.com the user will be redirected to http://abc.exmaple.com:8080/app. Wiki and blog access, as an exception in the configuration file. The following is the configuration file:
? View Code CONF

RewriteCond% {HTTP: Host} example \. Com $
RewriteCond% {HTTP: Host}! Www \. Example \. Com $
RewriteCond% {HTTP: Host}! Wiki \. Example \. Com $
RewriteCond% {HTTP: Host}! Blog \. Example \. Com $
RewriteRule app / (. *) Http://% {HTTP: Host} \: 8080/app / $ 1 [NC, R = 301]
RewriteCond% {HTTP: Host} example \. Com $
RewriteCond% {HTTP: Host}! Www \. Example \. Com $
RewriteCond% {HTTP: Host}! Wiki \. Example \. Com $
RewriteCond% {HTTP: Host}! Blog \. Example \. Com $
RewriteRule (. *) Http://% {HTTP: Host} \: 8080/app [NC, R = 301]
RewriteCond% {HTTP: Host} www \. Example \. Com $
RewriteRule ^ / $ http://% {HTTP: Host} / app / index.htm [NC, R = 301]
RewriteCond% {HTTP: Host} wiki \. Example \. Com $
RewriteRule ^ / (. *) $ Http://www.example.com/wiki/ $ 1
RewriteCond% {HTTP: Host} blog \. Example \. Com $
RewriteRule ^ / (. *) $ Http://www.example.com/blog/ $ 1

Third, after the fight, the server’s port 80 so that in the Apache. I intend to cut back to the first time the mod_proxy configuration, but found a fatal problem: Request ri Host content has been mod_proxy modified become configure the localhost in the file does not reflect real user request abc.example.com or the def.example.com. Moreover, the system is also required to support real-time add tenants that add new *. Example.com access not reboot the system.
mod_proxy any background HTTP service to do a reverse proxy, yet the pan-domain access to stand in the door. In addition, I finally understand why Tomcat test server access log source 127.0.0.1 – source Apache the proxy.
mod_jk configuration, although you still need to enter the Tomcat Host, but it seems AJP agreement retains the front desk domain name (daemon obtained through request.getServerName ()). The IP address of the client have been successfully recorded. Interested students can see the AJP 1.3 protocol reference. mod_jk configuration is not posted the concrete can see the beginning of the introduction proxy_ajp that link.

 Multi-domain apache configuration

Apache configure multiple domain names, generally two methods, virtual hosts and use mod_rewrite URL redirect or pseudo-chain ~
Virtual Host Configuration last simple add method in the httpd.conf file, for example:

<VirtualHost Www.ll19.com>
DocumentRoot usr/local/www/ll19
ServerName www.ll19.com
# ErrorLog logs / minidx.com-error_log
# CustomLog logs / minidx.com-access_log common
</ VirtualHost>
 
<VirtualHost Www.baidu.com>
DocumentRoot usr / local / www / baidu
ServerName www.baidu.com
</ VirtualHost>

So when access to the relevant domain name will jump to the corresponding directory the virtual host biggest drawback consumption performance, and seems to be used to host static files and APACHE connections and load balancing background mod_jk conflict, so personal do not recommend using the virtual host to manage the domain name.
Using mod_rewrite to redirect the domain name or pseudo-chain:

Mod_rewrite support, you first need to open the search in the httpd.conf file:

# LoadModule rewrite_module modules / mod_rewrite.so

Remove the # sign, open mod_rewrite, continue to search for change AllowOverride None to AllowOverride All, Open htaccess support. Note that AllowOverride can be set for each directory, there should be the apache DocumentRoot root path settings to AllowOverride All:

<Directory “/var/www/html”>
    AllowOverride All
</ Directory>

After the establishment. Htaccess file is placed under the DocumentRoot to manage the domain name by writing. Htaccess:

Domain name 301 redirect htaccess set:

RewriteEngine On
RewriteBase /
 
RewriteCond% {HTTP_HOST} ^ www.test.net.cn [NC, OR]
RewriteCond% {HTTP_HOST} ^ test.net.cn [NC]
RewriteRule ^ (. *) $ Http://www.test.com/test.html $ 1 [R = 301, L]
 
RewriteCond% {HTTP_HOST} ^ www.test.net [NC, OR]
RewriteCond% {HTTP_HOST} ^ test.net [NC]
RewriteRule ^ (. *) $ Http://www.test.com/test1.html $ 1 [R = 301, L]

Access www.test.net.cn, or test.net.cn the beginning of the domain name will jump to the beginning of http://www.test.com/test.html, www.test.net or test.net domain name will jump Go to http://www.test.com/test1.html.

Note that some of the symbols and parameters:

^ Www.test.net.cn to www.test.net.cn as at the beginning, and all languages! Behalf No, that,! ^ Www.test.net.cn said not to www.test.net.cn the beginning .

Of mod_rewrite legal template prefix, said “non” mean, this description does not meet certain matching conditions are very convenient, or as a last resort a default rule. Use! Can not be grouped wildcard in the template, not do backreferences.

R mandatory external redirect, can be followed on behalf of 301 or 302 jumps.

L indicates that the current rule is the last rule, stop the rewrite rules analyzed. (If any) satisfy the conditions

OR or mean domain on the the case both www.test.net.cn or test.net.cn the beginning.

NC is not case-sensitive.

$ N reference the RewriteRule template match string.

For example, in the previous example http://www.test.com/test.html $ 1, my personal test results:

Access http://www.test.net.cn/132 will jump to http://www.test.com/test.html132

This is a useful parameter, if removed $ 1 no matter http://www.test.net.cn the beginning of the address behind the link is, will ultimately turn to: http://www.test.com/test.html

Drawback is redirected to the domain name can not be preserved, it is not recommended, so the best way or the domain name pseudo-link set, writing is also very simple, remove the R = 301 is rewritten to the current server address path to:

Options + FollowSymLinks
 
RewriteCond% {HTTP_HOST} ^ www.test.net.cn [NC, OR]
RewriteCond% {HTTP_HOST} ^ test.net.cn [NC]
RewriteRule ^ (. *) $ / Test / cn / $ 1 [L]
 
RewriteCond% {HTTP_HOST} ^ www.test.net [NC, OR]
RewriteCond% {HTTP_HOST} ^ test.net [NC]
RewriteRule ^ (. *) $ / Test / net / $ 1 [L]

Access will jump to www.test.net.cn/ ** the corresponding localhot / test / cn / ** and related domain www.test.net.cn the will be retained.

Attachment: RewriteRule Parameter Detailed]

1) R mandatory external redirect, can be followed on behalf of 301 or 302 jumps.
2) F disabled URL, Back to 403HTTP status code.
3) G URL is GONE, Back to 410HTTP status code.
4) P is mandatory to use a proxy forwarding.
5) L indicates that the current rule is the last rule, stop the analysis after the rules rewrite.
6) N rewriting process again from the beginning of the first rule to run.
7) C is associated with the next rule.
8) T = MIME-type (force MIME type) the mandatory MIME type.
9) NS used to not only internal sub-request.
10) NC are not case sensitive.
11) QSA additional request string.
12) NE is not output escaping special characters.

There are many more things that you can do with mod_rewrite. As and when I discover more, I will keep updating this page.

Please feel free to post your usage of mod_rewrite

 

 

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>