preload preload preload preload

Apache URL Rewriting

Introduction 

One of the more powerful tricks of the .htaccess is the ability to rewrite URLs. This enables us to do some mighty manipulations on our links; useful stuff like transforming very long URL’s into short, cute URLs,  redirecting URL to some other URL, transforming dynamic ?generated=page&URL’s into /friendly/flat/links, redirect missing pages, preventing hot-linking, performing automatic language translation, and much, much more.

When you use rewrite rule you have to enable rewrite module in the apache.conf file and you have to restart apache again.

In Ubuntu you can use a2enmod to enable rewrite mod

#sudo a2enmod rewrite

#sudo /etc/init.d/apache2 restart

begin rewriting… 

First you have to add following lines to the Apache Virtualhost.

<Directory / Your Document Root>
Options FollowSymLinks
AllowOverride all
</Directory>

Simple rewriting

Simply put, Apache scans all incoming URL requests, checks for matches in our .htaccess file and rewrites those matching URLs to whatever we specify. something like this..

Example 1 :

all requests to whatever.htm will be sent to whatever.php:

# .htaccess file

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [nc]

Example 2 :

all requests to example.com will be sent to xyz.com

# .htaccess file

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

# require non-empty HOST header
RewriteCond %{HTTP_HOST} !^$

# require case-insensitive HOST to be www.example.net
RewriteCond %{HTTP_HOST} !^www\.example\.net$ [NC]

# 301 redirect everything to correct www.example.net
RewriteRule ^(.*)$ http://www.xyz.com/$1 [R=301,L]

# or you can use this rewriterule
#RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

  • Share/Bookmark
  • Leave a Reply

    * Required
    ** Your Email is never shared