Create Search Engine Friendly URLs with mod_rewrite

Search engine friendly URLs avoid the use of symbols when passing URL variables. Providing clean URLs adds to the user experience by removing characters neither your visitors nor search engines want to see.  In this article you will learn how to turn this http://domainname.com/forum.php?id=1 intohttp://domainname.com/forum/id/1/ using mod_rewrite.  

Introduction to mod_rewrite

Mod_rewrite is an apache module that allows URLs to be interrupted before the server processes them.  This buffer allows you to create human readable URLs that can be converted back into complex parameters by the server.  

Installation

Mod_rewrite can be used on any platforms. Mod_rewrite is included in the Apache 2 development package and can be installed on CentOS and Redhat using yum install apache2-devel. Mod_rewrite is installed with apt-get apache2 on Ubuntu but is not enabled by default. Run a2enmod rewriteto enable it.

Usage

Mod_rewrite can be used to perform very complex tasks; however, we can keep things very simple to create search engine friendly URLs.  Your mod_rewrite rules can be placed either in the apache configuration file or in an .htaccess file*. 

Below is all you need to turn this http://domainname.com/forum.php?id=1 intohttp://domainname.com/forum/id/1/.

Options +FollowSymLinks
RewriteEngine on
RewriteRule forum/(.*)/(.*)/$ /forum.php?$1=$2

*Additional steps will be required if placing the code in .htaccess results in error.  Adding this to the apache site container will allow it to work from .htaccess.  

Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

Options Indexes FollowSymLinks MultiViews 
AllowOverride all 
Order allow,deny 
allow from all

Relative Paths

Once you start using mod_rewrite you will most likely run into broken links using relative paths.  This side effect happens because a relative path starts where the URL stops.  Referencing anything after a modified URL will typically result in the file not being found.   To prevent broken images, CSS and JS files always refer to them with absolute paths.  In most cases you can simply change css/style.css to /css/style.css.

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

Installing htop

htop is an interactive process viewer for Linux, which is a powerful alternative to the...

Bind Multiple IP Addresses to a Single Network Interface Card (NIC)

This tutorial demonstrates how to bind multiple IP addresses to a single NICI'll be using LAN...

Clear Memory Cache on Linux Server

By default the Linux OS has a very efficient memory management process that should be freeing any...

Set the time on a Linux server

Log into the server via SSHAt the shell prompt run the following command:date MMDDHHmmYYYYFor...

Check your disk usage in Linux

A good way to check your disk usage for folders on your Linux server is via shell.Download...