Useful HTACCESS Examples

htaccess is a common file used by several web servers to control configuration for a directory. Using this file we can change the behaviour of the server. This file is used to Rewrite Urls and some other things which is described below.

Create a 404 Error Page

The 404 or Not found error tells that the client didn't get the requested file. And the default error page is displayed. We can create a custom error page using following code in .htaccess file and creating and error page named 404.php in following example.

Create a 404.php file in the root and put the following code in .htaccess file. It will display the customized error page.
    ErrorDocument 404 /404.php

Redirect non WWW to WWW

   RewriteEngine On
   RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
   RewriteRule ^(.*)$$1 [L,R=301]

Rewrite dynamic urls to look like static urls

   RewriteEngine on
   RewriteRule ^product-([^/]+).\html$ product.php?type=$1
   RewriteRule ^user/([^/]+)$ users.php?name=$1

The output of above rewrite examples will be 

Allow or Deny specific IP Addresses

   order allow,deny
   deny from
   deny from
   allow from all

Allow or deny specific IP Addresses using above code. Put your list of IP Addresses as given above.

Cache files using htaccess

  <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
  Header set Cache-Control "max-age=31449600, public"

Set an expiration for cache files using above code.

Disable directory listing using htacess

Directory listing may be a potential security risk on your site. When you enter any address of a directory into the browsers address bar, all files and folders af that directory are listed by default. To prevent this listing you can put a small piece of code in .htaccess file as follows.
   Options -Indexes

Useful HTACCESS Examples Useful HTACCESS Examples Reviewed by Altaf Hussain on January 26, 2013 Rating: 5

1 comment:

Altaf Web. Powered by Blogger.