WebHosting Blog

« Secure & Optimize VPS/VDS | Home | How to create Remote login page for cPanel »

mod_rewrite Tutorial

By bob | May 19, 2008

mod_rewrite simple tutorial

The potential of mod_rewrite is enormous that have many functionalities on Apache web server, It  also help if you  to hide the structure of your website and the script which passes the arguments. Here is the simple mod_rewrite tutorial.

This is your website www.domain.com
and you have a script which passes the arguments.
So your url look like this:
www.domain.com/index.php?query=xxx&id=yyy

mod rewrite enables you to change that into:
www.domain.com/xxx/yyy/

First of all make sure that mod_rewrite is available on your server and turned on.
You can check that out by creating a file (let’s call it phpinfo.php) with the following content:
PHP Code:
<? phpinfo(); ?>
Go to that page and search for mod_rewrite. If you find it you’re good to go.
If not, contact your host.

OK, now create a .htaccess file with this content:
Code:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)/(.*)/$ index.php?query=$1&id=$2 [L]

Upload the file to your server into the folder that contains the script.
Now when someone requests “something” on your server, it automatically gets transcribed to index.php?query=something&id=something

In case if you want your site to look like this:
www.domain.com/xxx-yyy.html
Follow this;
This is the setup for the .htaccess file:
Code:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)-(.*).html$ index.php?q=$1&id=$2 [L]

Now, you need to just update the links in your website and your site is SEO friendly and will hard to hack.
If you have static links you have no problems, but for instance if your script is generating the urls based on various conditions.
So here’s the old code:
PHP Code:
<html>
<body>


<?
echo ‘<a href=”$siteurl/index.php?query=type&id=$id”>Link</a>’;
?>
You’d change it to:
PHP Code:
<html>
<body>


<?
echo ‘<a href=”$siteurl/type/$id/”>Link</a>’;
?>
for the first type of url rewrite.
Or:
PHP Code:
<html>
<body>


<?
echo ‘<a href=”$siteurl/type-$id.html”>Link</a>’;
?>
for the second type.
Hope it helps.

Topics: Hosting Tools |

Comments