How to Enable mod_rewrite On Apache2 – Ubuntu

mod rewrite is an Apache module that enables us to give readable aliases (better known as ‘friendly URLS’) to our web pages. So instead of ‘myPages.php?page_number=12&pages_title=myAwesomePage’ I can use the url ‘my_pages/my-awesome-page’ instead.

Before we can do that, we have to enable this on our apache server. Here’s a quick reference on how it’s done on Ubuntu:

  • Open your favorite terminal and type at the prompt:
    sudo a2enmod rewrite
  • Next stage is to modifiy the general website definitions page. At the prompt type:
    sudo gedit /etc/apache2/sites-enabled/000-default
  • Edit these lines:

    DocumentRoot /var/www
    Options FollowSymLinks
    AllowOverride all
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order allow,deny
    allow from all
  • Next thing – we restart the apache server. At the prompt type:
    sudo /etc/init.d/apache2 restart
  • Now, you can give your rewrite rules inside the .htaccess file. This file should be located in the root directory of your website. If it’s not there – create a text file and save it as .htaccess (begins with a dot). At the top of this file type:RewriteEngine On
  • Inside this file we set the rewrite rules. For instance – We have on our site a file named bob.html, and a file named alice.html. But we want whoever goes to alice.html, to be redirected to bob.html. So our .htaccess file looks like this:
    RewriteEngine on
    RewriteRule ^alice.html$ bob.html

    We can also use regular exressions to define more general rules for pages. For instance: this rule will redirect the pages: 1-my-awesome-page-1 and 2-my-awesome-page-2 to the file: index.php?page=1 and index.php?page=2 respectively:

    RewriteRule ^(d)-.+/?$ index.php?page=$1 [L]

That’s it!