How to use mod rewrite to simplify URL Rewriting in Apache â A basic guide to the mod rewrite modu


Introduction


URL Rewriting is the manner of manipulating an URL or a link, which is dispatch to a lattice server in such a bag that the link is dynamically modified at the server to subsume fresh parameters and news along with a server initiated redirection. The lacework server performs all these manipulations on the fly so that the browser is kept outside of the loop regarding the interchange mythical in URL and the redirection.


URL Rewriting can good your websites and mesh based applications by providing bigger security, more select visibility or friendliness with Search Engines and helps in carefulness the constitution of the website extra little to nurture for likely changes.


You can scrutinize approximately the idea and benefits of URL Rewriting from my Preceding article, which can be accessed from here. In this article we testament be fascinating a double o at how we can utensil URL Rewriting on an Apache based netting server world using the mod_rewrite module for Apache.


What is mod_rewrite?


Mod_rewrite is one of the most favoured modules for the Apache net server and there are countless interlacing developers and administrators who will plebiscite this module as the beyond compare concern to happen on Apache. This module has a piece of tricks up its sleeve so that it can be called the Swiss Army Frog sticker of all Apache Modules. Apart from providing elementary URL Rewriting functionality for an Apache based website, this module arms the website with more advantageous URL protection, fitter search engine visibility, safeguard against bandwidth thieves by stopping feverish linking, harass cuffo restructuring possibilities and options to arrange friendliest of URLs for the website users. This module due to its versatility and functionality can at times mood a bit daunting to master, however getting a finished patient of the basics can construct you a crackerjack of the art of URL Rewriting.


Lets Begin! â " A contemplate at all the effects you desideratum to get on your assessment sphere to obtain mod-rewrite alive and kicking.


First and foremost you should chalk up a properly configured Apache Web Server on your crack machine. Mod_rewrite is normally installed along with the Apache server, on the contrary in context it is lost â " this can be the occasion on a Linux mechanism where the mod_rewrite module was not compiled along with the installation â " you will hold to buy it installed. For using mod_rewrite on your Apache box you will carry to configure this module to load dynamically on require false by Apache. On a shared server you will bear to contact your web hosting gathering to amuse this module installed and loaded on Apache.


On your community computer you can asset whether the module is installed along with Apache by having a contemplation at the modules directory of Apache. Probation for a document named mod_rewrite.so and provided it is there then the module can be specious to load in to the Apache server dynamically. By default this module is not loaded when Apache starts and you demand to advise Apache to enable this module for driving loading by forming changes in the web servers configuration file, which is explained below.


How to Enable mod_rewrite on Apache?


You can accomplish the mod_rewrite module load dynamically in to the Apache web server nature using the LoadModule Decree in the httpd.conf file. Load this folder in a matter editor and boast a contour agnate to the one addicted below.


#LoadModule rewrite_module modules/mod_rewrite.so


Uncomment this column by removing the # and save the httpd.conf file. Restart your Apache server and if all went hearty mod_rewrite module will instantly be enabled on your web server.


Lets Rewrite our headmost URL using mod_rewrite


Ok, first off the mod_rewrite module is enabled on your server. Lets corner a inspect at how to arrange this module load itself and to build it labour for us.


In categorization to load the module dynamically you hold to add a unmarried path to your .htaccess file. The .htaccess files are configuration files with Apache directives defined in them and they fit distributed directory alike configuration for a website. Actualize a .htaccess case in your web servers research directory â " or any other directory on which you wish to dash off URL Rewriting active â " and add the below inclined edge to it.


RewriteEngine on


Now we gain the rewrite engine turned on and Apache is ready to rewrite URLs for you. Lets gaze at a illustration rewrite instruction for moulding a interrogate to our server for first.html redirected to second.html at server level. Add the below prone border to your .htaccess string along with the RewriteEngine notice that we acquire added before.


RewriteRule ^first.html$ second.html


I will excuse what we posses done here at the following section, nevertheless if all went husky then any requests for first.html imaginary on your server will be transfered to second.html. This is one of the simplest forms of URL Rewritting.


A purpose to notice here is that the redirect is kept completetly covered from client and this differs from the classic HTTP Redirects. The client or the browser is obsessed the conception that the content of the second.html is duration fetched from first.html. This enables websites to build on the fly URLs with away the clients awareness and is what makes URL Rewriting ideal powerful.


Basics of mod_rewrite module


Now we discriminate that mod_rewrite can be enabled for an all-inclusive website or a particular directory by using .htaccess dossier and keep done a basic rewrite edict in the previous example. Here I will diagram what licence retain we done in the basic standard rewrite.


Mod_rewrite module provides a place of configuration ordinance statements for URL Rewriting and the RewriteRule command - that we axiom in the previous guideline - is the most critical one. The mod_rewrite engine uses pattern-matching substitutions for production the translations and this mode a fine grasp of Typical Expressions can facilitate you a lot.


Note: Universal Expressions are so all-inclusive that they will not fit in to the scope of this article. I will one's damndest to autograph another article on that topic someday.


1. The RewriteRule Directive


The regular syntax of the RewriteRule is correct straightforward.


RewriteRule Ornament Substitution [Flags]


The Mannequin allotment is the design which the rewrite engine will beholding for in the incoming URL to catch. So in our ahead morals ^first.html$ is the Pattern. The base is written as a habitual expression.


The Substitution is the replacement or translation that is to be done on the caught mould in the URL. In our principles second.html is the Substitution part.


Flags are optional and they adjust the rewrite engine to act persuaded other tasks apart from even-handed doing the substitution on the URL string. The flags if extant are defined with in square brackets and should be separated by commas.


Lets obtain a see at a and compound rewrite rule. Yield a glom at the adjacent URL.


http://yourwebsite/articles.php?category=stamps&id=122


Now we will interchange the above URL in to a search engine and user civil URL affection the one liable below.


http://yourwebsite/articles/stamps/122


Create a event called articles.php with the closest code:


$category = $_GET['category'];


$id = $_GET['id'];


echo "Category : " . $category . " ";


echo "ID : " . $id;


This leaf simply prints the two Bias variables passed to it on the webpage.


Open the .htaccess information and copy in the below habituated Rule.


RewriteEngine on
RewriteRule ^articles/(w+)/([0-9]+)$ /articles.php?category=$1&id=$2




The imitation ^articles/(w+)/([0-9]+)$ can be bisected as:


^articles/ - checks if the appeal starts with 'articles/'


(w+)/ - checks if this detail is a single colloquy followed by a forward slash. The parenthesis is used for extracting the parameter values, which we committal for replacing in the actual suspicion string, in the substituted URL. The pattern, which is placed in parenthesis will be stored in a exceptional variable which can be back-referenced in the substitution belongings using variables allying $1, $2 so on for everyone couple of parenthesis.


([0-9]+)$ - this checks for digits at the behind item of the url.


Try requesting the articles.php list in your analysis server with the below inured url.


http://yourwebsite/articles/coins/1222


The URL Rewrite law you include written will kick in and you will be seeing the conclusion as if the url requested where:


http://yourwebsite/articles.php?category=coins&id=1222


Now you can occupation on this example to cause expanded and besides compounded URL Rewritting rules. By using URL rewriting in the above action we admit achieved a search engine and user amicable URL, which is and tamper evaluation against informal script kiddie injection category of attacks.


What does the Flags parameter of RewriteRule dictate do?


RewriteRule flags feed us with a street to authority the contrivance mod_rewrite handles each rule. These flags are defined inside a universal locate of square brackets separated by commas and there are about 15 flags to choose from. These flags gamut from those which controls the expedient rules are interpreted to composite oneâ s love those which sent specific HTTP headers back to the client when a match is erect on the pattern.
Lets gander at some of the basic flags.



  • [NC] flag (nocase) â ". This makes mod_rewrite to treat the motif in a case-insensitive manner.

  • [F] flag (forbidden) â " This makes Apache mail a forbidden HTTP response header â " response 403 - back to the client.

  • [R] flag (redirect) â " This flag makes mod_rewrite to end a formal HTTP redirect instead of the internal Apache redirect. You can apply this flag to inform the client about the redirection and this flag sends a Moved Temporarily - Response 302 - by default, on the other hand this flag takes an additional parameter, which you can advantage to exchange the response code. If you ambition to letter a response decree of 301 â " Moved Permanently â " then this flag can be written as [R=301]

  • [G] flag (gone) â " This flag makes Apache respond with a HTTP Response 410 â " Record Gone.

  • [L] flag (last) â " This makes mod_rewrite to closing processing closest directives if the ongoing order is successful.

  • [N] flag (next) â " This flag makes the rewrite engine to location growth and loop back to day one of the edict list. A objective to memo is that the URL, which will be used for example matching, will be the rewritten one. This flag can contrive an endless loop and so severe affliction should be disposed while using it.


There are other flags very but they are circuitous to disclose with in the scope of this article so you can pride extended counsel on them by referring the mod_rewrite manual.


2. The RewriteCond Directive


This directive gives you the further gift of conditional checking on a area of parameters and conditions. This statement when combined with RewriteRule will let you rewrite URLs based on the boom of conditions. RewriteCond are cherish the if() statement in your programming speech but here they are for deciding if a RewriteRule directiveâ s substitution should return distance or not. Matters coextensive preventing ardent linking and checking whether the client meets decided criteriaâ s before rewriting the URL etc can be achieved by using this directive.


The public syntax of the RewriteCond is:


RewriteCond string-to-test condition-pattern


The string-to-test object of the RewriteCond has access to a big establish of Variables compatible the HTTP Header variables, Offer Variables, Server Variables, Generation variables etc so you can end a group of manifold conditional checking while writing directives. You can practice any of these variables as a column to check by putting it in a %{string} format. Suppose you demand to bag the HTTP_REFERER variable then it can be used as %{HTTP_REFERER }.


The occasion branch can be a not difficult contour or a bare mingled usual expression as your belief is the matchless string with this module.


Lets takings a flash at an ideal for conditional rewriting using RewriteCond directive:


RewriteCond %{HTTP_USER_AGENT} ^Mozilla/4(.*)MSIE
RewriteRule ^index.html$ /index.ie.html [L]
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/5(.*)Gecko
RewriteRule ^index.html$ /index.netscape.html [L]
RewriteRule ^index.html$ /index.other.html [L]


This paradigm uses the HTTP_USER_AGENT as the attempt edge with the RewriteCond directive. What it does is that it uses the HTTP_USER_AGENT header variable to catch the browser of the visiting user and match it against a allot of pre certified values to detect the browser and serve at odds pages to the guest based on the match result. The first off RewriteCond checks the HTTP_USER_AGENT to bonanza a match for the ^Mozilla/4(.*)MSIE pattern. This match will arise when a user visits the folio using IE as browser. Then the RewriteRule accustomed aloof under that statement will kick in and will rewrite the URL to server index.ie.html sheet to the IE visitor.


Similarly a checking is trumped-up for mozilla specific browsers in the moment RewriteCond and the RewriteRule will complete the substitution for index.netscape.html when a good match is untrue on the ^Mozilla/5(.*)Gecko pattern. The third RewriteRule is there to receive other browsers. If both the antecedent and second RewriteCond fails then the endure RewriteRule will be considered. A speck to communication in the above instance is the usage of the [L] flag with all the RewriteRule directives. This is used to avoid the cascading of applying the rules when a convinced RewriteRule is applied.


Two flags which can be used to very government the groove the RewriteCond directive behave are [NC] â " case-insensitive â " and [OR] â " chaining of multiple RewriteCond directives with logical OR.


By using these two directives â " RewriteRule and RewriteCond â " you can device a abundance of powerfull URL Rewriting functionality on your website.


Other mod_rewrite Directives



  1. RewriteBase Directive â " This directive can solve the crunch of RewriteRule creating non-existent URLs due to deviation in the physical data development structure on web server and the structure of website URLs. Setting this directive to the below apt statement can solve this problem.
    RewriteBase /

  2. RewriteMap Directive â " This directive is also dynamic as it allows you to map onliest values to a fix of other replacement values from a table and to capitalization it in the substitution to practise on the fly URLs. This can be remarkably all-purpose for vast e-commerce or CMS altruistic of applications where you commitment to modify each intersect term or sort flag in the URL with a homogenous id taken from a database.

  3. RewriteLog Directive â " This directive can be used to set the log file that the mod_rewrite engine will custom to log all the actions taken during processing on client requests. The syntax is:
    RewriteLog /path/to/logfile
    This directive should be defined in the httpd.conf file as this directive is applied on a per-server basis.

  4. RewriteLogLevel Directive â " This directive tells mod_rewrite module the proportions of counsel on the internal processing done while rewriting URLs to be logged. This directive takes values from 0 to 9 where 0 way no logging and 9 method all the confidence is logged. A higher common of logging can conceive Apache pace slow, so a akin above 2 is desired solitary for debugging purposes. This directive can be applied using the below given syntax.br/>
    RewriteLogLevel levelnumber


Conclusion


In this article we keep taken single a petite eyeful at the efficacy of the mod_rewrite module. It is one a scratch on the surface but I dream it is sufficiently to influence you started on using this module on your web server environment.

Comments: [0] / Post comment:

Keywords:

apache, apache server, rewriting apache, apache basic, makes apache, loaded apache, along apache, apache based, apache pace, apache respond