Apache Re-Writes in .htaccess

March 29th, 2009 * 4 Responses

apache logo
In this post I will walk you through an example scenario that will use an apache re-write to clean up the URL to make it more SEO friendly and human readable, which as I briefly touched upon in my last post, is very important for the search engine optimization of your website.

Scenario

Members Site – Profiles

Lets say our members site has 4 members, each of which has their own profile page, containing information stored in a database. To access this page we want to be able to use the URL:

www.example.com/profile/[username]

The Set Up

Database

If we set up a table in our database and create the following table: -

database

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
--
-- Table structure for table `users`
--
 
CREATE TABLE `users` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `age` int(3) NOT NULL,
  `tel` varchar(13) NOT NULL,
  `location` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
 
--
-- Dumping data for table `users`
--
 
INSERT INTO `users` VALUES(1, 'stew', 22, '0154684874', 'Doncaster');
INSERT INTO `users` VALUES(2, 'Oli', 24, '01132648745', 'Leeds');
INSERT INTO `users` VALUES(3, 'Craig', 24, '0208548765', 'London');
INSERT INTO `users` VALUES(4, 'James', 21, '01777648465', 'Retford');

And create a very simple profile page:

Profile.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	<?php
 
	//Set up our database connection	
	mysql_connect('localhost', 'root', 'root');	
	mysql_select_db('example');
 
	//Get the username variable from the URL and asign it to the variable user	
	$user = $_GET['username'];	
	$query = "SELECT * FROM users WHERE username = '$user'";	
	$result = mysql_query($query);
 
       //while there are values within the results array, make them equal to $x
	while($x = mysql_fetch_array($result)){		
		echo "<h1>". $x['username']."</h1><br>";
		echo "<b>Age:</b> ". $x['age']."<br>";
		echo "<b>Telephone:</b> ".$x['tel']."<br>";
		echo "<b>Location:</b> ".$x['location']."<br>";	
	}	
       //close the mysql connection
	mysql_close();
 
	?>

If you visit the page profile.php you will see that nothing appears, because we have not fed a username into the url. If you add the following to the end ‘?username=’Stew’, providing there is an entry in the database for a Stew, a profile along with some basic information will appear on the screen.

screen print

But this URL is not human readable, user friendly or SEO friendly, so we now have to trick our web server into thinking they are seeing this URL. We can do this using a simple .htaccess file located in the root folder of the website. The file will tell the server that when it see’s the clean URL, what it is actually seeing is in fact the dirty, ugly URL, leaving both parties happy.

Ensuring mod_rewrite is enabled

We just have to make a quick check to ensure that your apache server is set-up to handle the re-writes before we start.

In a new file called info.php simply type:

        <?php phpinfo(); ?>

and point your web browser to that page, scrolling down to the ‘loaded moudles’ section, look for ‘mod_rewrite’. If you can’t find it then this site should help you to enable it.

.htaccess

With mod_rewrite enabled we can now write our .htaccess file. Create a new file in your root folder, and called ‘.htaccess’, within the file add the following

1
2
3
RewriteEngine on
 
RewriteRule ^profile/([^/\.]+)/?$ profile.php?username=$1 [L]

RewriteRule breakdown

  • ^profile – checks if this rule applies (“does the url start with this”)
  • ([^/\]+) – the brackets tell the rule to remember the matching data. The rules [^/\]+ means anything except forward and back slash is acceptable
  • /?$ – Ensures there is nothing except a forward slash after the information else the rule is skipped
  • profile.php?username=$1 – Tells appache which page to actually load, with $1 being replaced with the captured variable
  • [L] – Makes sure no other rules are used if this one is successful

Testing

With the htaccess file saved, we must first restart appache, then if we visit:

…/profile/James

screen print

you will see the profile on ‘James’ we can change ‘James’ to any of the usernames in the database and the displayed data will change accordingly

Well thats about all for this post/tutorial but please subscribe to my blog for more tutorials

Tags: , , ,

You can leave a response, or trackback from your own site.

4 Responses to “Apache Re-Writes in .htaccess”

  1. Tom Says:

    March 30th, 2009 at 7:15 am

    Nice to see a good, simple mod_rewrite example to help people learn, especially including some practical code to help demonstrate it in action. When I first had to deal with it, something like this would have been very useful.

    As a side note, I know the PHP here is just a simple example to demo the .htaccess functionality, not a full app, but for learners reading this it may be useful to use something like…

    $user = mysql_real_escape_string($_GET['username']);

    …just in case this app is useful to them as a basic PHP/MySQL tutorial also.

  2. Tom Says:

    March 30th, 2009 at 7:17 am

    Oops… I should have said:
    “… to help avoid SQL injection attacks.” ;)

  3. Stew Parkin Says:

    March 30th, 2009 at 9:12 am

    Very good point Tom, but as you pointed out, the php code is only simple, and should NOT be used on any production server!

  4. Vijendra Says:

    April 3rd, 2009 at 12:41 pm

    Nice shot … gr8 article .

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • Newer Entries »