StepsURL rewriting using Mod_Rewrite


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


The following are two examples of a URL before translation:


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


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:

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:


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


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:


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


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
Post Comment
Copyright © 2017
- All Rights Reserved.
Thank you!