News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

The RewriteCond Statement

Started by sukishan, Aug 22, 2009, 06:53 PM

Previous topic - Next topic

sukishan

The RewriteCond Statement
Now that you've learned how to use mod_rewrite's basic RewriteRule statement with the {REQUEST_URI} string, it's time to see how we can use conditionals to access other variables with the RewriteCond statement. The RewriteCond statement is used to specify the conditions under which a RewriteRule statement should be applied.

RewriteCond is similar in format to RewriteRule in that you have the command name, RewriteCond, a variable to be matched, the regex, and flags. The logical OR flag, [OR], is a useful flag to remember because all RewriteCond and RewriteRule statements are inclusive, in the sense of a logical AND relationship, until terminated by the Last, [L], flag.

You can test many server variables with a RewriteCond statement. You can find a list in the SitePoint article I mentioned previously, but this is the best list of server variables I've found.

As an example, let's assume that we want to force the www in your domain name. To do this, you'll need to test the Apache {HTTP_HOST} variable to see if the www. is already there and, if it's not, redirect to the desired host name:

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

Here, to denote that {HTTP_HOST} is an Apache variable, we must prepend a % character to it. The regex begins with the ! character, which will cause the condition to be true if it doesn't match the pattern. We also have to escape the dot character so that it matches a literal dot and not any character, as is the case with the dot metacharacter. We've also added the No Case flag to make this operation case-insensitive.

The RewriteRule will match zero or one of any character, and will redirect to http://www.example.com plus the original {REQUEST_URI} value. The R=301, or redirect, flag will cause Apache to issue a HTTP 301 response, which indicates that this is a permanent redirection; the Last flag tells mod_rewrite that you've completed this block statement.

RewriteCond statements can also create atoms, but these are denoted with %1 ... %9 in the same way that RewriteRule atoms are denoted with $1 ... $9. You'll see these atom variables in operation in the examples later on
A good beginning makes a good ending