Clean URLs Using Apache’s mod_rewrite and PHP - Beginner’s Tutorial
In technology, there’s always the goal of making complex and difficult things more simple - this goal has brought about ‘clean URLs’. Clean URLs are website addresses that are easy for people (and also search engines) to read and understand. For example: An interesting article about the Bermuda Triangle might be at www.articles.com/article.php?id=23452 - That address tells us (and search engines) nothing about the article. Using a clean URL, the same article might be at www.articles.com/articles/bermuda-triangle - much easier, right? Well, here is how you can implement this on your website…
Setting Up Apache’s “mod_rewrite” Modul
To implement these URLs with Apache, you will need to have the mod_rewrite module enabled. Here’s how to enable mod_rewrite:
- Open the httpd.conf file from the …apache/conf/ directory
- Uncomment the line “LoadModule rewrite_module modules/mod_rewrite.so” (by removing preceding #)
If you have more than one virtual server or directory set up, you might have to add something like this as well:
<Directory "PATHOFDIRECTORY">
AllowOverride all
Order allow,deny
Allow from all
</Directory>
Next, you need to create a file named “.htaccess” at the website’s root directory (if you haven’t got one already)
In your .htaccess file, add the following rules:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
This will redirect all requests that don’t point to an existing file or directory to ‘index.php’.
You might (or might not) be thinking “How does that help implement clean URLs?” The next part will answer that question, but before proceeding - test your new Apache config and .htaccess file - restart Apache if necessary and try loading a directory that doesn’t exist (ie. http://yourwebsitehost/page/5/your-information/). If it loads your index.php page - we’re ready to continue.
Getting PHP to Interpret The URLs
Ok, the hard part is done. Now I’ll explain what we want when a user requests a page:
- User requests “/page/5/your-information/”
- Apache redirects the request to “index.php” without changing the user’s URL
- index.php breaks up the requet URI and loads page.php instructing it to load page ‘5′
This might seem a bit difficult (or, if you’re experienced, very easy) - it honestly is rather easy. Once you understand how it works, you might decide to do it differently, but here is a really simple example of a website that contains information ‘pages’ and information about the ‘authors’ of those pages.
In our example, we have three php files:
- index.php
- page.php
- author.php
“index.php”
<?php
//$urlVariables is an array that contains the different bits of information in the request.
$urlVariables = explode("/",$_SERVER['REQUEST_URI']);
//If the user requested '/page/6/about-elephans/' then $urlVariables[1] would be 'page', $urlVariables[2] would be '6' and so on.
if ($urlVariables[1] == "page") {
//the user is requesting an information page
include "page.php";
} elseif $urlVariables[2] == "author" {
//the user is requesting author information
include "author.php";
} else {
//load the home page
include "default.php";
}?>
“page.php”
<?php//load an object that deals with pages (to keep the tutorial simple) include "classes/page.php"; $page = new page;//$urlVariables will contain the page id as the 2nd array element (ie. /page/pageid/page-name-here/)$page_id = $urlVariables[2]; //the page name part of the URL is ignored when loading because we only use ID to load pages - it's just good for search engines and people. //get the page class to load the page if ($page->load_page($page_id)) {?> <h1><?php echo $page->page_name(); ?></h1> <p><?php echo $page->page_content(); ?></p> <p>Written by <a href="<?php echo $page->author_url(); ?>"> <?php echo $page->author_name(); ?> </a></p><?php } else { //error! include "error.php";}>
“about.php”
<?php
//load an object that deals with authors (again, to keep the tutorial simple)
include "classes/author.php";
$author = new author;
//$urlVariables will contain the page id as the 2nd array element (ie. /author/authorid/author-name-here/)
$author_id = $urlVariables[2];
//again, the author name part of the URL is ignored when loading because we also only use ID to load authors - it is just good for search engines and people.
//get the author class to load the page
if ($author->load_author($author_id)) {?>
<h1><?php echo $author->author_name(); ?></h1>
<h2>Bio</h2><p><?php echo $author->author_information(); ?></p>
<h2>All pages by <?php echo $author->author_name; ?></h2>
<$php echo $author->page_list;
} else {
//error!
include "error.php";
}
?>
Now that example was probably a bit excessive. Here’s a basic overview of how it works:
- The index.php page is loaded, and ‘explodes’ the request part of the URL into an array ($urlVariables in the example)
- You then interpret the array elements to decide what to show to the user. ($urlVariables[1] determined whether to show a page or an author profile and $urlVariables[2] was an ID for either the page or the author in our example)
It’s that simple. This method is SUPER flexible if you build a strong framework around it.
Good luck!




IDIOMS development » Blog Archive » Front end research links
[...] Basic rewriting: http://www.logon2.com.au/blog/archive/web-design/php-apache-mod-rewrite-tutorial/ [...]
February 17, 2008 @ 9:05 am
babysitter
this is my .htaccess file but when I write a not real folder i get file not found, why?:
#
# Apache/PHP/Drupal settings:
#
# Protect files and directories from prying eyes.
Order allow,deny
# Don’t show directory listings for URLs which map to a directory.
Options -Indexes
# Follow symbolic links in this directory.
Options +FollowSymLinks
# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php
# Force simple error message for requests for non-existent favicon.ico.
# There is no end quote below, for compatibility with Apache 1.3.
ErrorDocument 404 “The requested file favicon.ico was not found.
# Set the default handler.
DirectoryIndex index.php
# Override PHP settings. More in sites/default/settings.php
# but the following cannot be changed at runtime.
# PHP 4, Apache 1.
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0
# PHP 4, Apache 2.
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0
# PHP 5, Apache 1 and 2.
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0
# Requires mod_expires to be enabled.
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
# Do not cache dynamically generated pages.
ExpiresByType text/html A1
# Various rewrite rules.
RewriteEngine on
# If your site can be accessed both with and without the ‘www.’ prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the ‘www.’ prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the ‘www.’ prefix,
# (http://example.com/… will be redirected to http://www.example.com/...)
# adapt and uncomment the following:
# RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
# RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
#
# To redirect all users to access the site WITHOUT the ‘www.’ prefix,
# (http://www.example.com/… will be redirected to http://example.com/...)
# uncomment and adapt the following:
# RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
# RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal
#
# If your site is running in a VirtualDocumentRoot at http://example.com/,
# uncomment the following line:
RewriteBase /
# Rewrite URLs of the form ‘x’ to the form ‘index.php?q=x’.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L]
# $Id: .htaccess,v 1.90.2.3 2008/12/10 20:04:08 goba Exp $
order allow,deny
allow from all
deny from 150.70.84.155
deny from 150.70.84.45
March 24, 2009 @ 11:01 am
Vecymact
order colon cleanse colon cleanse injury attorney ohio = colon cleanse drink colon cleanse 75 mg drug = 2mg india 100 pills with free dr consultation
February 6, 2010 @ 1:03 pm