Friendly Dynamic Pages

You have probably noticed how all the articles here have nice looking addresses, and it isn’t some “script.php?id=4” page. Well in this tutorial I’m going to show you how I did it.

The first thing you are going to need to do, is come up with some type of naming scheme. For instance, all the articles are /articles/ID/keywords here. Then once you have that, you’ll also need the script which will be doing the dynamic part of all this.

What we will be doing, is just redirecting any requests that look like the naming scheme, and pull up the script instead of looking for the actual page. We do this by using the htaccess RewriteRule.

RewriteEngine on
RewriteRule ^articles/1\.html$ scripts/articles.php?id=1

The first thing to note: Before you can use the RewriteRule command in your .htaccess file, you need to use the RewriteEngine command. Otherwise you’ll get server errors.

This basic example shows us how the syntax works, and you can easily see what it is doing. Note that when you use the RewriteRule, the browser doesn’t know it at all. It is just telling the server “Hey, show them this page instead”.

Now if you want to have this dynamically allowed, you would need to use some regular expressions. Using the following code would allow any #.html article to be redirected:

RewriteRule ^articles/([0-9]+)\.html$ scripts/articles.php?id=$1

Just like in a normal regular expresion, you use the $1 symbol to put what was found in the parnthasis in its place. The reason we have 0-9 is so only numbers are used, and the + tells it to allow more than one. This will allow articles/99.html – but not articles/free.html

Now the numbers still don’t look to good for users. Search engines will like the .html extension, and no question mark gibberish. But users won’t be able to remember the article numbers of their favorites if they want to pick from their history. So thats why I have the keywords section on CLiX Network.

To do it, its simple:

RewriteRule ^articles/([0-9]+)/(.*)$ scripts/articles.php?id=$1

Here the added /(.*) allows for any characters, and it makes the url look like a directory structure. If you want to pass the keywords to the script like I do, below is the code:

RewriteRule ^articles/([0-9]+)/(.*)$ scripts/articles.php?id=$1&keywords=$2

Now why would I go and do that? Simply because the script will send a redirect to the browser if the keywords are incorrect. This will help if someone just changes the article number, and not the keywords. If they do that and like the article, they may confuse themselves.

So there you have it! Enjoy! (In case you were wondering, even if you do this you can still Cache and Compress your page with PHP. The reason is because the server knows its a php page, even though the browser thinks its a .html or directory)