Menu Close

mod_rewrite

The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly. By default,mod_rewrite maps a URL to a filesystem path. However, it can also be used to redirect one URL to another URL, or to invoke an internal proxy fetch.

For mor einformation about mod-rewrite , please check http://httpd.apache.org/docs/current/mod/mod_rewrite.html

We only explain How to use mod-rewrite here.

the easiest way to check whether the mod_rewrite module is installed will be to look on your phpinfo page. If you’ve not already created one of these for yourself, just copy and paste the following code into an new text file using your favourite text editor, save it as phpinfo.php, and upload it to your server:

<?php phpinfo(); ?>

Load that page up in your web browser, and perform a search for “mod_rewrite”. All being well, you’ll find it in the “Apache loaded modules” section of the page.  Assuming the mod_rewrite module is loaded, then you’re good to go!

 The structure of a RewriteRule

RewriteRule Pattern Substitution [OptionalFlags]

Here is a short explanation of each part:

    1. RewriteRule
    2. This is just the name of the command. The section in which you can write in the name of the the mod_rewrite directive that you want to use.You can add as many RewriteRule lines as you like to your .htaccess file. mod_rewrite works through the rules one at a time, processing any rules that match the requested URL.If a rule rewrites the requested URL to a new URL, that new URL is then used from that point onward in the .htaccessfile, and might be matched by another RewriteRulefurther down the file. (If you don’t want this to happen you can use the L (“last”) rule, described in a moment.)
    3. Pattern
    4. This section is dedicated to interpreting the requested URL, using regular expressions. A regular expression which will be applied to the “current” URL. If any RewriteRules have already been performed on the requested URL, then that changed URL will be the current URL.
    5. Substitution
    6. Substitution occurs in the same way as it does in Perl, PHP, etc. This is the actual URL of the page with the information we want to display. It may be hard to remember or confusing because of php paremeters or long strings of numbers. eg. www.cityzoo.com/animals.php?mammals=seals
    7. You can include backreferences and server variable names (%{VARNAME}) in the substitution.
    8. Backreferences to this RewriteRule should be written as $N, whereas backreferences to the previous RewriteCond should be written as %N.A special substitution is -. This substitution tells Apache to not perform any substitution. I personally find that this is useful when using the F or G flags (see below), but there are other uses as well.
    9. Optional Flags
    10. This is the only part of the RewriteRule which isn’t mandatory. Any flags which you use should be surrounded in square brackets, and comma separated. A flag is a tag at the end of the Rewrite Rule directive that may change the behavior of of the expression. Some common flags include [F], making the URL forbidden, [NC], forcing the rule to disregard capitalization, [R=301] or [R=302], controlling the redirect code you want to use, [L] indicating that this is the last rule in a series. This is the only part of the RewriteRule which isn’t mandatory. Any flags which you use should be surrounded in square brackets, and comma separated. The flags which I find to be most useful are:
      • F – Forbidden. The user will receive a 403 error.
      • L – Last Rule. No more rules will be proccessed if this one was successful.
      • R[=code] – Redirect. The user’s web browser will be visibly redirected to the substituted URL. If you use this flag, you must prefix the substitution withhttp://www.somesite.com/, thus making it into a true URL. If no code is given, then a HTTP reponse of 302 (temporarily moved) is sent.
    11. A full list of flags is given in the Apache mod_rewrite manual.

 Examples of mod_rewrite applications

1. Redirect old-url.html to new-url.html


RewriteEngine on
RewriteRule ^old-url\.html$ /new-url.html [R=301,L]

The RewriteRule works like this:

^old-url\.html$
The regular expression that will match the URL to rewrite. This pattern means: “Match the start of the URL (^), followed by the text 'old-url.html', followed by the end of the URL ($)”.
^ – The Start of the Match
$ – The End of the Math
\ – before the “.” and make the math of dot as “.” With regular expressions, a dot (.) means “match any character”. So, to explicitly match the dot in 'old-url.html', you need to place a backslash (\) before the dot to escape it, as shown in the regular expression above.
/new-url.html
The second part of the RewriteRule is the URL that you want to use instead. In this case, this is simply /new-url.html.
[R=301,L]
The third, optional Flag part of a RewriteRule is one or more flags, separated by commas and surrounded by square brackets. These flags let you add specific options and actions to the rule. In this case there are 2 flags: R=301 means “issue a 301 redirect to the new URL”, and L means “last rule” — in other words, “stop processing if this rule matched the requested URL”.

2. Make a Search Engine Friendly URL

Check out this URL:

http://mydomain.com/results.php?products=iphone

It would be much clearer displayed as:

http://mydomain.com/products/iphone

The lines within the .htaccess file would look like this:

RewriteEngine on
RewriteRule ^products/([A-Za-z0-9-]+)/?$ results.php?products=$1 [NC]

  • ^products: In order to be caught and rerouted, the URL must start with products (keep in mind that this only refers to the text after the domain name). It can begin with anything else.
  • ([A-Za-z0-9-]+): The content within the parentheses refers to any information that could be typed into the URL. In other words, the URL will be rewritten to reflect whatever a visitor to the site inputs after /products/.
  • +: The plus sign indicates what is in the brackets can be one or more characters (as opposed to, say, a single character that is either a letter or a number).
  • /?$: the dollar sign points out the end of the string. The question mark allows the last character in the string to be a forward slash (although it does not require it).
  • results.php?products=$1: the $1 indicates where the string from the pattern should go. In other words, it will put in the information captured from whatever people wrote in the “([A-Za-z0-9-]+):” part. After the process completes, the browser will display the information from the second URL
  • [NC]: this is a flag at the end of the phrase, indicating that the rule should ignore the cases of all of the characters in the string.