Wednesday, January 3, 2018

.htaccess Tutorial

What is .htaccess? Its a simple ASCII text file that resides in your site's main directory and/or any other directory. Some of the main uses of .htaccess are to include personalized error pages, redirection, password protection and alot more. This file requires "mod_rewrite" to be enabled

.htaccess Tutorial

What is .htaccess?

htaccess stands for Hypertext Access, which is default name for Apache configuration file. Lets not confuse .htaccess with an extension its rather a filename. This file affects any directory it resides in, which can be either website's root directory or any sub-directory.

How to create .htaccess file?

You don't need any special program for creating .htaccess file just simple text editor would be enough. When you save .htaccess file just keep in mind this file has no name just ".htaccess" extension so when you save choose "All Files" in file type box and file name should be only ".htaccess".

Error Redirection with .htaccess

You can redirect users to specific pages when they try to access invalid pages. For example if a user tries to visit a page that does not exist causing 404 error. To handle this redirection with .htaccess command would be like this:
ErrorDocument 404 /404.html 

Common Error Codes:

Code Description
400 Bad Request
401 Unauthorized
403 Forbidden Access
404 Not Found
500 Internal Server Error
502 Bad Gateway
504 Gateway Timeout

Custom Redirection with .htaccess

However if you ever wanted to redirect a specific old page to any new page you can also do that with .htaccess. To do that with .htaccess command would be like this:
Redirect /OldDir/OldFile.html /NewDir/NewFile.html 

Password Protection with .htaccess 

You can also password protect your web pages with .htaccess. To achieve this you will need to create a new file (.htpasswd) that houses all the username and passwords. You have to create ".htpasswd" file same as you created .htaccess. This file .htpasswd will contain usernames and password in the following format:
admin:123456
user:123123
Now that you have created .htpasswd you need to add the following code in your .htaccess file. Remember this password protection will apply on the directory ".htaccess" resides in and all the subdirectories.
AuthUserFile /absolute/pathto/.htpasswd
AuthType Basic
AuthName "Authorization Required"
require valid-user

Deny Users via IP Address

You can also restrict visitors from specific IP Address from viewing your web pages. For example if you wanted to block IP "199.155.88.25" the code would be as below:
order allow,deny
deny from 199.155.88.25 
allow from all 
NOTE: .htaccess file requires "mod_rewrite" to be enabled.