Monday, 5 August 2013

SEO friendly URLs with htaccess and PHP include script

This is one of the guide for SEO-friendly URLs with .htaccess.

People always used PHP include script to include websites subpages.
However, it doesn't look too good when the URL says "www.mysite.com/index.php?page=home".
It looks much better as "www.mysite.com/home".
In this guide I'll show you how to use PHP include script and combine it with SEO friendly URLs.

To create SEO friendly URLs all you need is a little file called .htaccess.

Step 1
Open up your text editor and type the following:
---------------------------------------------------------------------------
RewriteEngine On
RewriteRule ^([^/.]+)/?$ /index.php?page=$1
---------------------------------------------------------------------------
Save this as .htaccess and upload to your webserver.
If you type www.yoursite.com/example, the Apache web server will now interpret it as www.yoursite.com/index.php?page=example

Step 2
The SEO friendly URLs should work now, but you also need a PHP script that will include the subpages.
The following script is set to include all pages from a directory called "inc", but change it to whatever you like.
Note: This should be in your index.php file where the main content appear.
---------------------------------------------------------------------------
<?php
$page = $_GET['page'];

$def = "home";
$dir = "inc";
$ext = "php";

if (isset($page)) {
    $page = substr(strtolower(preg_replace('([^a-zA-Z0-9-/])', '', $page)), 0, 20);
    if (file_exists("$dir/$page.$ext") and is_readable("$dir/$page.$ext")) {
        include("$dir/$page.$ext");
    }
    else {
        include("$dir/error404.$ext");
    }
}
else {
    include("$dir/$def.$ext");
}
?>
---------------------------------------------------------------------------

Step 3
Change all internal links and replace them with your new SEO links.
For example, if you have a link to index.php?page=about, change this to about.


You're finished! Open your website and try to enter the short SEO friendly URL. :)


About Author:
Manish Chandak  is social media enthusiast and works as business analyst with Systems Plus Pvt. Ltd. He in free time reads and write on various technologies and process around social media. He can be contacted at: manish.c@spluspl.com

No comments:

Post a Comment