How To Enable mod_rewrite In Ubuntu

The mod_rewrite is Apache’s very powerful URL manipulation module. It may seem somewhat complex to beginners. This module comes the default with Apache setup. By default its disabled. Let see how to enable mod_rewrite in Ubuntu.

Apache has very simple but very useful command a2enmod to enable Apache modules. You can run this command using terminal from any directory. We are going to use this command to enable mod_rewrite module as well. Enter following in terminal:

$ sudo a2enmod rewrite 
$ sudo service apache2 restart

Now open default site configuration:

$ sudo gedit /etc/apache2/sites-available/000-default.conf

000-default.conf file may have contained following content:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

We need to add <Directory> directives, allow to override URL manipulation done using .htaccess. Your file finally will look like follow:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html 
    #OR DocumentRoot /var/www depending on your setup

    <Directory />
        Options FollowSymLinks
        AllowOverride All
    </Directory>

    <Directory /var/www/html/> 
    #OR <Directory /var/www/> depending on your setup
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

If <Directory> directives are already there you just need to change AllowOverride from none to All.

Now restart Apache service using this command:

$ sudo service apache2 restart

Yes! That’s it…. Pretty simple huhh? Wanna test your changes? Lets do it…

Create one php file phpinfo.php in your server root (mostly /var/www/html/ or /var/www/) with following inside it.

<?php phpinfo(); ?>

Now create .htaccess file at your server root with following rewrite rule inside.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /phpinfo.php [L]
</IfModule>

Above rules will map any non-existing file or directory URLs to phpinfo.php file. Suppose you have example directory inside your server root and you are trying to visit URL http://localhost/example, it will work. If you have a file example2.php on your server root and if you visit URL http://localhost/example2.php, it will work too. But if you visit any URL for those directories or files not present on your server it will open phpinfo.php file instead. Lets check by visiting URL http://localhost/yourname or http://localhost/yourname.php.

Leave a comment

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