KwikSteps

StepsURL rewriting using Mod_Rewrite

by

One of the modules used in an Apache web server is Mod_Rewrite. The module is installed on most of the servers running Apache. The main usage of this module is to change and translate URL parameters. Unlike redirect methods, this process is done without the knowledge of the user or the browser. Mod_Rewrite can increase the security of your website and make it search engine optimized (SEO).

Article Image

Example:

The following are two examples of a URL before translation:

http://localhost/content.php?id=How-To-Mod-Rewrite
http://localhost/content.php?id=200

The following is an example of the same URL after translation:

http://localhost/How_To_Mod_Rewrite/

Step 1: Check if Mod_Rewrite is activated

There are two ways to check if Mod_Rewrite is enabled on the server. The first method is to run the following command:

a2enmod rewrite

If it is already activated, it will display the following:

Module rewrite already enabled

The other method is to use phpinfo() and look for the module under Loaded Modules. To do this, create a php file with following content:

<?php 
echo phpinfo(); 
?>

Step 2: Enable the .htaccess file:

First, you need to make sure that .htaccess is enabled on your site. To do this, you will need to check the Apache configuration (httpd.conf or apache2.conf) and to make sure that the following is set under <Directory> where your website is located.

AllowOverride All

Make sure to restart the Apache server after making any changes to its configuration.

Step 3: Create or edit the .htaccess file:

Let’s look again at our first example above. Let’s assume that we have created a php page called conent.php with a content id parameter as shown below:

http://localhost/content.php?id=How-To-Mod-Rewrite

Now we want to translate the URL into a friendly URL like this one:

http://localhost/How-To-Mod-Rewrite/

To do this, we will create or open our .htaccess file located in our web page directory and add the following code to it:

RewriteEngine on
RewriteRule ^([A-Za-z0-9-]+)/?$ content.php?id=$1 [NC]

Line 1 in this code will turn on the rewriting engine.
Line 2 will tell the server to substitute the “How-To-Mod-Rewrite” into content.php?id=How-To-Mod-Rewrite

Step 4: Pagination

Now let’s assume that your web page has multiple pages where the user can go to page 2 then to 3 and so on. As shown in the following URL:

http://localhost/content.php?id=How-To-Mod-Rewrite&Page=2

To translate the URL into a friendly URL like this one:

http://localhost/How-To-Mod-Rewrite/2/

We need to add the following line to our .htaccess file:

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ content.php?id=$1&Page=$2 [NC] 

You can read more about Mod_rewrite here:

Comments (2)
Load comments
Post your comment
*Name:
Email:
*Comment:
Post Comment
logo203X28
Copyright © 2017
KwikSteps
- All Rights Reserved.
Thank you!
Namecheap.com