Enable mod_rewrite Apache on Ubuntu Server - BLog.CripperZ.SG

New Post has been published on http://blog.cripperz.sg/2013/08/12/enable-mod_rewrite-apache-on-ubuntu-server/

Enable mod_rewrite Apache on Ubuntu Server

At first I should define, what is mod_rewrite?
mod_rewrite is a part of Apache server that can rewrite requested urls on the fly.

To enable mod_rewrite in Ubuntu, you just need to write this command in terminal

sudo a2enmod rewrite

After enabling mod_rewrite you can write .htaccess file for your web application.

So what is .htaccess?
.htaccess file provides a way to make configuration changes on a per directory basis. It is a file contains configuration directives is placed in a particular document directory and the directives apply to that directory and all subdirectories thereof.

Some example:

Nice looking URLs (no querying) with pagination:
Suppose your url is: domain.com/article.php?name=title&page=5
You want to change: domain.com/articles/title/5/
Then write in .htaccess file:
RewriteRule ^articles/(A-Za-z0-9-]+)/([0-9]+)/?$ article.php?name=$1&page=$2 [L]

The rule is defined in regular expression. Here [L] means Last Rule. It’s called RewriteRule Flags.

Another example:
Suppose your site has permanently moved to a new domain.
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule  ^(.*)$ http://www.domain2.com/$1  [R=301, L]

Here [NC] means case insensitive and its called RewriteCond Flags. [R=301] means moved permanently. Its called redirection header code.

Source Article @ http://blog.cripperz.sg/2013/08/12/enable-mod_rewrite-apache-on-ubuntu-server/