Breaking News
You are here : Home / Web development / htaccess / Apache URL Rewrite Beginner Guide
Apache URL Rewriting

Apache URL Rewrite Beginner Guide

 

INTRO TO APACHE URL REWRITING:- URL Rewriting is a way to produce Search Engine Friendly URLs.Also these URLs can easily be Remembered by the visitors.URL Rewriting is not the Easiest game.you should be careful  in some steps.As rewriting provide great functionality so it should be Implemented carefully.I recommend you to test first then Implement the technique.I assure you that URL rewriting is very Powerful Tool.

Understanding Apache URL Rewrite:- In Dynamic Content Websites we use URL rewriting to get rid of the QueryString and produce simple URLs.Most of the CMS softwates use url Rewrites.

Now suppose we have a blog with several posts.each post has a id,id is mostly integer,so we pass get variables to get the specified post by id like:

http:// www.example.com?postid=2

this kind of URL is not easily remembered by users so it can be converted to something like below:

http:// www.example.com/post/2

the above one is much cleaner can easily to remember,or we can further make it much better like below.the post name in url.Just need to have a url alias field in your blog table and store the unique alias for particular alias for each post.

http:// www.example.com/sample-post

But the thing is that the above URL cannot be directly understood by the server.So there is a module named Apache URL Rewrite to Implement this one.So lets start the with the basic’s the apache URL rewrite.

REQUIREMENTS:

In APACHE web server you need to have Mod Rewrite module enabled .this is the module which translate the URLS.

And Also you need to know the basic’s of the regular expressions.

GETTING START:

Consider a simple PHP page as

http:// www.example.com/this-is-sample-page.php

now we want to reduce it in to form of

http:// www.example.com/sample-page

which is shorter URL and good.

so to convert this URL we need to tell our apache web server to take the url request ‘sample-page’ and redirect it internally to ‘this-is-sample-page.php’.

we want all that action inside server so that URL in browser remain simple.

SO to achieve this goal we need to Create a file in the root directory of our server.file must be named as .htaccess. the .htaccess file will have our rules to rewrite.Be careful about the name .htaccess . (.httaccess) it should be just .htaccess nothing after or before. not even any extension just .htaccess .If there is already a .htaccess that it is much better. open it and start writing you rules.

Now open the file and add the following code:

RewriteEngine On # Turn on the rewriting engine

RewriteRule ^sample-page/?$   this-is-sample-page.php  [NC,L]  # Handle  “sample-page” requests

Now lets Understand the above code:

The first line ‘RewriteEngine On’ tells the apache web server to to turn on the rewriting Engine.The line should only be written once only for your .htaccess file.

Now lets move to second line ‘RewriteRule’ .This is the main code for the internal redirection .we broke the line in smaller parts as:-

  • RewriteRule – Tells Apache that this like refers to a single RewriteRule.
  • ^/sample-page/?$ – The “pattern”. The server will check the URL of every request to the site to see if this pattern matches. If it does, then Apache will swap the URL of the request for the “substitution” section that follows.
  • this-is-sample-page.php – The “substitution”. If the pattern above matches the request, Apache uses this URL instead of the requested URL.
  • [NC,L] – “Flags”, that tell Apache how to apply the rule. In this case, we’re using two flags. “NC”, tells Apache that this rule should be case-insensitive, and “L” tells Apache not to process any more rules if this one is used.
  • # Handle requests for “sample-page” – Comment explaining  the rule  (optional but recommended)

The above rule is simple and the base for all URL rewrites.But the above rule is just meant for single URL.Now we go towards Regular Expressions to implement it more Dynamic way.

Regular Expressions And pattern Matching:-

So say we wana change multiple URLs with just the one rule.SO how we gonna do ,so we have Regular expressions for that.

suppose we have many posts in our web Blog.and we wana rewirte a single rule for then,Lets take a look

the URLs of posts will be

http:// www.example.com/post.php?postid=2

and what we want it to look like

http:// www.example.com/post/2

so we have a numeric value 2 which is telling which post to load

http:// www.example.com/post/{number}

so this no could be any.so we won’t write multiple rules,rather we write a single regular expression for a number.which will be applied to our all posts.[0-9] means all the numbers

here is our rule

RewriteRule ^post/([0-9]+)/?$  post.php?postid=$1  [NC,L]  # Handle post requests

see we have packed our pattern [0-9] in brackets for the ‘back reference’.which refers to the substitution part of our condition.So $1 means the pattern we written in parenthesis.The “$1” in the  tells Apache to put the very first bracketed pattern in the URL and complete the request. You can have as many back references you need and they are numbered in the order they appears in rule.

e.g if you write http://www.example.com/post/1 then apache will internally rewrite URL like http://example.com/post.php?postid=1

Lets Digg Furthur:-

The above examples might have cleared the basic about the URL rewrites.Now we move on and see some Regular Expressions.you can perform lot of tricks using these regular expressions.

Here are some Important regular Expression Symbols:

  • . ( matches any character)
  • * (zero of more of the preceding)
  • + (one or more of the preceding)
  • {} (minimum to maximum quantifier)
  • ? (ungreedy modifier)
  • ! (at start of string means “negative pattern”)
  • ^ (start of string, or “negative” if at the start of a range)
  • $ (end of string)
  • [] (match any of contents)
  • – (range if used between square brackets)
  • () (group, backreferenced group)
  • | (alternative, or)
  • \ (the escape character itself)

so while using these symbols You might be very care full cause they have their meanings.

for example if you’d like to map www.example.com/sitemap.xml to www.example.com/sitemap.xml

RewriteRule ^sitemap.xml$  sitemap.php [NC,L]  #This is Wrong  

The above one is incorrect and the dot(.) between sitemap and xml will match all the characters like ‘sitemapxml’,’sitemap xml’. which is a problem.so you need to escape these characters as

RewriteRule ^sitemap\.xml$  sitemap.php [NC,L]  

Now the above is correct.

Now lets start getting more dynamic.consider the URLs below.

http:// www.example.com/profile.php?uid=25641&content=photos

so id here is numeric and content is alphabetic.we want URL to be like

http:// www.example.com/25641/photos

we interpret it as

http:// www.example.com/{number}/{alphabet}

so we gonna write the Rule as:

 RewriteRule  ^([0-9-])+/([A-Za-z-]+)/?$  profile.php?uid=$1&content=$2  [NC,L]  

The rule above will rewrite all the requests that will be match this pattern.That is all for the beginner level.Hope you like this Apache URL rewrite Rule.If you like please share it,hit like and Vote up…..

Tags : , , ,

3 Replies

  1. SB says:

    Very imformative. Nice article.

  2. SB says:

    can i ask, sir?

    how will i right, from let say, localhost/post/post.php?select=photos&photoid=12 into localhost/post/photomatch?select=photos&photoid=12.

    is that posible sir?

    Thanks in advance.

Leave a Reply

Want to join the discussion ? Feel Free to contribute !