Create Search Engine Friendly(SEF) websites in PHP using URL rewriting

Search Engine Friendly URL

Search Engine Friendly URL

This article is for beginners who want to learn how to create search engine friendly(SEF) URLs (or Clean URLs) for a website. I am considering that you are using Apache web server. For clean URLs we need to do URL rewriting.

Note:- The “mod_rewrite” module should be enabled in Apache httpd.conf file.

We can define our rewrite conditions and rewrite rules in httpd.conf file but on shared hosting we don’t have access to this configuration file. So, In that case we can define these conditions and rules in ‘.htaccess’ file.

‘.htaccess’ file provide configuration settings on per-directory basic. You need to place this .htaccess file in your server’s root directory.

We need to put the following code in our .htaccess file.

<IfModule mod_rewrite.c>
  RewriteEngine on
 
  # 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,QSA]
</IfModule>

First, we are checking ‘mod_rewrite’ module is available and loaded by Apache web server. If this module is loaded then only our rewrite rule work.

Then we need to ‘ON’ RewriteEngine.

In rewrite conditions we are checking few things. Like in

RewriteCond %{REQUEST_FILENAME} !-f

we are checking the given file/path is not a file.

RewriteCond %{REQUEST_FILENAME} !-d

we are checking the given file/path is not a directory.

If the above two conditions satisfy than only our rewrite rule apply to the given URL. We are doing this because if browser request any resource like JavaScript or CSS or Image files than we don’t want to rewrite those URLs. If any path/URL which does not exist on our server will be rewrite by RewriteRule. All such type of requests will be handled by index.php file.

For example, If we write

http://www.websitename.com/article/25
(This URL is not exist on our server)

in address bar then this URL is rewritten as

http://www.websitename.com/index.php?q=article/25

Now, the only thing we need to do is to handle all the requests properly in our index.php file. We can create a file ‘url.inc’ for handling all the conditions and include it in top of our index.php file.

<?php
/*url.inc file*/
 
$url = @explode($_GET['q']);
 
if (isset($url[0]) && $url[0] == 'article' && isset($url[1]) && isnumeric($url[1])) {
	include('article.php'); 
	exit();	
}
else if (some other condition) {
	// include some other file
	exit();
}
?>

If any of the condition mentioned in the ‘url.inc’ file not match then index.php files content will execute.

<?php
/*index.php file*/
 
include('url.inc'); 
 
echo "This is the index.php file."
 
?>

, , ,


  1. No comments yet.
(will not be published)


Submit Comment
Subscribe to comments feed