Apache mod_rewrite setup

This module provides a rule-based rewriting engine to rewrite requested URLs on the fly. Let’s see how to set it up and working in a few steps.

It comes bundled with Apache HTTP Server. To install Apache server on Linux:

apt-get install apache2


yum install apache2

then enable the mod (not enabled by default)

a2enmod rewrite

Now we are going to enable application specific settings on the apache server.

  1. Go to /etc/apache2/sites-available/
  2. Open default for editing.
  3. Replace AllowOverride None with AllowOverride All
<Directory /var/www/>
	Options Indexes FollowSymLinks MultiViews
	AllowOverride All
	Order allow,deny
	allow from all

All left is to check if it’s working. Since we’re going to need PHP install it and restart apache.

apt-get install php5 libapache2-mod-php5
/etc/init.d/apache2 restart

Enter the root directory of the web app you want to use mod_rewrite with.
Make index.php:

	echo "http://" . $_SERVER['HTTP_HOST']  . $_SERVER['REQUEST_URI'];

Open/Make a file .htaccess and add the following lines:

RewriteEngine on
RewriteRule ^.*$ index.php

This rule will redirect everything that comes to your web app to index.php inside the same app, and print the full address.

A good mod_rewrite cheat sheet can be found here. (courtesy of AddedBytes)

Tagged , ,

One thought on “Apache mod_rewrite setup

  1. […] wrote how to set up Apache HTTP server and mod_rewrite (which comes bundled with it) and redirect all requests to a single […]

Leave a Reply to How to make an URL Shortener (with code in PHP and MySQL database) » The (Code) Den Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.