mod_rewrite Tutorial

First to check if your mod_rewrite is enabled. Check phpinfo.php if you see mod_rewrite, it is enabled. If you do not see it, it is not necessary mean your server is not enabled. You may wish to go to following address to check further: http://www.wallpaperama.com/forums/how-to-test-check-if-mod-rewrite-is-enabled-t40.html

Put it simple, mod_rewrite is just to find a matched string pattern in user’s input URL, and to replace it by the substitution string. So, the center of mod_rewrite is RewriteRule, which is responsible for the match and replace. The rest directives are just for setting purpose. The most used configuration directives other than RewriteRule are RewriteEngine, RewriteOptions.

RewriteEngine’s common value is:
On – This is because default value for this directive is off.

RewriteOptions’ common value is:
Inherit - This forces the current configuration to inherit the configuration of the parent.

RewriteRule’s syntax is:
RewriteRule Pattern Substitution [Flag]

Pattern needs to be bracketed by anchors ^youInputURL$. Pattern consists of two parts, the static substring you known already and those dynamic part. You do not need to change any for static substring, while you would need to group the dynamic part. The grouping can be done by bracket (). There are also two parts inside of (), first is the character class grouping by [], and second is the flag to tell whether the character class has only one character or nil, or more, etc. The character class is ruled by RegExp.

Following is the syntax for the pattern:
(text) - Grouping of text
[chars] - Character class: One of chars
[^chars] - Character class: None of chars
text1|text2 - Alternative: text1 or text2
? - 0 or 1 character of the preceding text
* - 0 or N character of the preceding text
. - 1 character of the preceding text
+ - 1 or N character of the preceding text
\char - escape that particular char, for instance to specify the chars ".[]()" etc.

The substitution consists of two parts, the static string and the dynamic part as grouped in preceding pattern. The second is always shown as $1.

Flag’s syntax is [SOMETHING, SOMETHING, SOMETHING]. SOMETHING is the flag. Following are common used flags:
NC - This makes the input pattern case-insensitive.
L - Stop the rewriting process here and don't apply any more rewriting rules. Use this flag to prevent the currently rewritten URL from being rewritten further by following rules.

Example:
RewriteEngine On
RewriteOptions Inherit
RewriteRule ^([A-Za-z0-9-]+)$ /php/main.php?uname=$1 [NC,L]


http://corz.org/serv/tricks/htaccess2.php
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html
http://www.workingwith.me.uk/articles/scripting/mod_rewrite

No comments:

Post a Comment

Labels