Use your left/right keys to browse tutorials
Mod rewrite in 10 minutes

Mod rewrite in 10 minutes

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on March 2, 2009

Mod rewrite is the best tool to rewrite those long and complicated urls. So what do you need to use mod_rewrite? The only thing you need to get started is make sure that the mod_rewrite module is installed in your Apache server. If your not sure how to find out fear not, copy the code below (make sure you put it between php delimiters) save it and upload it to your server and visit the page. If it isn’t there, you’ll have to contact your hosting company and ask them to add it to the Apache configuration.

phpinfo();

Assuming the mod_rewrite module is installed, then we’re good to crack on with the next stage. Copy the code below save it as your .htaccess file and upload it to your servers root directory.

RewriteEngine On

#This is the bit that does the rewrite
RewriteRule ^contact/$ /pages/contact.html [NC,L]

So what’s the code doing?

Lets take a look at the code. So we’ve started by telling apache to turn on the rewrite engine, this now allows us to perform url rewrites now. Simply put, apache recognises the url structure and redirects it to the second part of the rewrite rule. Each time you perform a rewrite rule you must start by writing ‘RewriteRule’ followed by the url structure.

To make the code above work, upload the above .htaccess file and simply create a new html document and add some dummy text. Save it in the folder ‘pages’ and upload it to your server root, for example: www.papermashup.com/pages/contact.html.

if you now visit your site url /contact/ for example www.papermashup.com/contact/ you should see the html file in the folder ‘pages’.

So how can you pass variables through the url? Simple. Here’s an example below. The url we are writing to is as follows.

www.yourdomain.com/user/ashleyford/blog/papermashup

you can see that after ‘user’ in the code below we can expect either letters between a-z or numbers from 0-9 and that after ‘blog’ we are only looking for a number from 0-9. So what if you have more than 2 Get variables in your url? for each variable continue the structure as shown below but increment the values $1, $2, $3, $4 and so on within your url structure.

#This is the bit that does the rewrite
RewriteRule ^user/([a-z0-9]+)/blog/([0-9]+)$ pages/blog.php?id=$1&blogid=$2 [NC,L]

Rewrite rule Flags

You can see that we are using [NC,L] at the end of the rule, ‘NC’ means that it is not case sensitive so there is no difference between A-Z and a-z. ‘L’. Use this flag to prevent the currently rewritten URL from being rewritten further by following rules.

Common Flags

NS Use the following rule for whenever you prefix URLs with for example, CGI-scripts to force them to be processed by the CGI-script.

NE This flag keeps mod_rewrite from applying the usual URI escaping rules to the result of a rewrite. Ordinarily, special characters (such as ‘%’, ‘$’, ‘;’, and so on) will be escaped into their hexcode equivalents (‘%25′, ‘%24′, and ‘%3B’, respectively); this flag prevents this from being done. This allows percent symbols to appear in the output.

There are more flags which can be seen here

This is a basic introduction to Mod_rewrite and the possibilities are endless when it comes to its use. If you have any questions please leave them below and i’d be more than happy to answer them.



More tutorials from Papermashup
Comments
9 discussions around Mod rewrite in 10 minutes
  1. Its-Me-SB says:

    Good post buddy,

    tell me sir, if the url is .com/index.php?page=page3911

    how do it make it go .com/p/page3911 ??

    thank you

  2. Pingback: Schöne Urls im CMS - Mod Rewrite sei dank - Code & Blog | SteviesWebsite Blog

  3. Paperboy says:

    Hi, do you have any tips on how to mod rewrite to redirect urls that shows up in my 404 log with &usg=blabla123123 in the end on many of my articles.

    So that this article (or any article) for example would redirect from:
    http://papermashup.com/mod-rewrite-in-10-minutes&usg=dsl146kdggklang145fkidhksjbf

    to:
    http://papermashup.com/mod-rewrite-in-10-minutes

    Thanks,
    Paperboy

    • Ashley says:

      Hey Paperboy,

      If i’ve understood your question right you want to redirect all 404 errors. you can add this to your .htaccess file to and change the links to your custom 404 page etc

      ErrorDocument 403 /frameworks/pages/error.php

      ErrorDocument 404 /frameworks/pages/error.php

      ErrorDocument 500 /frameworks/pages/error.php

      Ashley

  4. Adam S says:

    Err… reading your piece a little closer, I see the regex was intentional. Damn. Sorry.

    • admin says:

      Hey Adam,

      No problem, great to hear your feedback, good point with the Chain rules i will make an amendment to the post to include the most popular. Let me know if you’d like to write a guest post on WordPress mod_rewrite rules as it sounds like a good post to me!

      Thanks

      Ashley

    • admin says:

      Made an update, added a few Rewrite flags :)

  5. Adam S says:

    Hi Ashley,

    You have a small error in your final rewrite script. Your second regex, after the /blog/ section, is only going to match numbers, but your url is expecting “papermashup.” You need this to be your final rewrite rule:

    RewriteRule ^user/([a-z0-9]+)/blog/([a-z0-9]+)$ pages/blog.php?id=$1&blogid=$2 [NC,L]

    It would be worth explaining how to chain rules, what the NC, L, and other designators and flags mean too.

    I think the basic WordPress mod_rewrite rules are really pretty cool, and you should definitely explain them. If you need some help, let me know, I’d be glad to assist.





Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.