News Ticker

Some useful htaccess snippets for website developers

By Ajay Verma - Friday 13 November 2015 No Comments
Snippet 1: Password Protected Directory:
If you want to protect using Basic authentication, place a .htaccess file in the directory containing
the protected file/s:
AuthName "Please Enter Password"
AuthType Basic
AuthUserFile /home/username/.htpasswd
Require valid-user

How To Set Password:
Add .htaccess and .htpasswd files permissions of 644.
For the first user, say unknowndevice64, we have to create file hence we will use -c and run it as
htpasswd -c /home/username/.htpasswd unknowndevice64
And enter the password for the user and then run it again, without the -c option, for more users if
you want to add.

Snippet 2: Providing Custome error pages/message:
ErrorDocument 404 ud64/404.html
For Example
ErrorDocument 404 "Error.. Page not Found !"

Snippet 3: How to add www to a URL
RewriteEngine on
RewriteCond %{HTTP_HOST} ^unknowndevice64\.info$
RewriteRule ^(.*)$$1 [R=301]

Snippet 4: Blocking a Specific IP Address
Below Code will block Ip
RewriteCond %{REMOTE_ADDR} ^(64\.64\.64\.64)$
RewriteRule (.*) - [F,L]

Snippet 5: Prevent Directory Browsing
When there's no index page in a directory, visitors can look and see all documents.
Below Code Will Prevent Indexing
Options All -Indexes

Snippet 6: Custome directory Index file
We can change a default index file of directory with:
DirectoryIndex unknowndevice64.html unknowndevice64.php

Snippet 7: Detecting Tablets and Redirecting
below code will redirect tablet-based users to a particular web page or directory:
RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ [R=301]
RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ [R=301]

Snippet 8: Hotlink Protection
Concerned about direct access to image files, use below code will redirect to defined file:
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)? [nc]
RewriteRule .*.(gif|jpg|png)$ [nc]

Snippet 9: Force user to download files rather than view them:
AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

Snippet 10: Redirect Browser to https
This is always useful for those who have just installed an SSL certificate:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

No Comment to " Some useful htaccess snippets for website developers "