Sam Brown

RewriteRule examples for Simple PHP Pages

“Ever created a web site that was not big enough for a CMS but you did want to use PHP includes to save you some editing time in the future? Here is a nice way to get rid of those nasty, non search engine friendly URLs and replace them with clean URLs.”

It is very easy to use PHP Includes to separate content from design. On several occasions I have created a site that had a static design, it had several pages, and the content for each page sat within the same area in the design. Why create 10 pages with the design when you can create 1 and include the different content dynamically!

My client did not have a huge budget so instead of creating a CMS I used PHP includes on a template page that called content pages into the design in a set place. This way if something was to be changed in the design it would require one change to the template, and not 10 changes to all of the pages.

Using PHP Includes to create a design template

Once the design is created, a single template page is coded and named index.php with the following code at the top of the file:

  1. <?
  2. $file = $_GET['page'];
  3. if( isset($_GET['page']) && file_exists("/path/to/file/$file.html") ) {
  4. $input = "/path/to/file/$file.html";
  5. } else {
  6. $input = "/path/to/file/main.html";
  7. }
  8. ?>
  9. Download this code: /code/rr_step1.txt

Within the coded template file you place the below code where you would like the content from the separate files to be placed:

  1. <?php include('$input'); ?>
  2. Download this code: /code/rr_step2.txt

When a page is called like so: [or]

The content from the contact.html page is placed where you have placed the code from step 2, if the file does not exist, main.html is put there instead (this should be your homepage content). Pretty simple once you get the hang of it.

RewriteRule for the .htaccess file

Unfortunately using this method leaves you with some pretty undesirable URLs: ?page=about [or] ?page=contact for example. These kinds of pages do not get indexed by search engines very well at all. So with the use of the RewriteRule and htaccess we can create some clean URLs for your website:

  1. Options +FollowSymLinks
  2. RewriteEngine on
  3. RewriteRule (.*)/(.*)/$ /index.php?$1=$2
  4. Download this code: /code/rr_step3.txt

This code, when placed inside a .htaccess file in the same directory as your index.php file will allow you to change your hyperlinks from: [to]

These URLs are optimized for search engines, are a lot cleaner, nicer and easier for your visitors to remember. This makes implementing them on your website a definite must, a little time spent cleaning things up is time well spent!

Post a link to this on Twitter ↩



Commenting has closed for this article. Feel free to me.
