gallery w3resource

what can you do with .htaccess


This slide presentation shows some important stuff you can do with .htaccess.


What is .htaccess?

.htaccess files are simple text files used to configure web servers. .htaccess files come handy when you don’t have access to the native web server configuration file (like in shared servers) but you need to configure the web server for redirecting or rewriting some web pages, block and allow access to certain hosts etc.

In the following slides we will see some of the things we can do with .htaccess. Note that, unlike the web server’s main configuration file, you don’t need to reboot your server when you are making some changes in the .htaccess file, changes are effected immediately instead.


Redirect 301 ^old\.html$ http://localhost/new.html

Adding the above to the .htaccess file will make sure that whenever somebody visits old.html she will be redirected to new.html

url rewriting

RewriteEngine on
RewriteRule ^old\.html$ new.html

URL rewriting allows you to completely separate the URL from the resource.

Serving Custom Error Pages

ErrorDocument 404 "/404.html"

This serves a custom page when a particular page is not found, instead of the default 404 error page.

Restricting Access to Specific Resources

AuthName "Username and password
AuthUserFile /path/to/.htpasswd
Require valid-user
AuthType Basic

Using .htaccess files, we can enable password protection of any file or directory, to all users, or based on things like domain or IP address.

Block Access to Certain Entities

order allow,deny
deny from
allow from all

To block a specific IP address, simply add the above directives to your .htaccess file

Deny requests based on user-agent

RewriteCond %{HTTP_USER_AGENT}
RewriteRule ^(.*)$ http://%
{REMOTE_ADDR}/$ [r=301,l]

In this example, any client with a HTTP_USER_AGENT string starting with OrangeSpider (a bad bot) is redirected back to the address that it originated from.

Force an IE Rendering Mode

Header set X-UA-Compatible "IE=Edge"

Adding this above to an .htaccess file will instruct IE to use the highest rendering mode available.


ExpiresActive on
ExpiresByType image/gif"access plus 1 month"
ExpiresByType image/png"access plus 1 month"
ExpiresByType image/jpg"access plus 1 month"
ExpiresByType image/jpeg"access plus 1 month"
ExpiresByType video/ogg"access plus 1 month"
ExpiresByType audio/ogg"access plus 1 month"
ExpiresByType video/mp4"access plus 1 month"
ExpiresByType video/webm"access plus 1 month"

Using ExpiresByType directive you can set expiry time for different static content and in turn can speed up your website.

Follow us on Facebook and Twitter for latest update.