The .htaccess file is a powerful configuration tool used on Apache-based web servers to control various aspects of website behavior. While it’s just a simple text file, it allows you to implement redirects, enhance security, set custom error pages, and more—directly from your hosting environment.
Most Unix/Linux-based hosting environments that use the Apache web server support .htaccess. However, not all hosting providers allow users to utilize it.
Check support:
If your host offers folder-level password protection, .htaccess is likely supported.
Test by uploading a .htaccess file with a basic command, or contact your host directly.
Some of the most common uses include:
Custom error pages (e.g., 404, 500)
Password protection for directories
IP-based access restrictions
URL redirection and rewriting
Disabling directory listings
Setting alternative index files
Create a .htaccess file using a plain text editor like Notepad.
To save properly:
Use the filename ”.htaccess” (include the quotes when saving in Windows).
If not allowed, save as htaccess.txt and rename it via FTP after uploading.
⚠️ Note: Avoid editing .htaccess if your site uses Microsoft FrontPage Extensions—these rely on their own .htaccess configuration.
Define custom error responses using this format:
ErrorDocument 404 /notfound.html
Common error codes:
401 – Unauthorized
403 – Forbidden
404 – Not Found
500 – Internal Server Error
To prevent users from viewing the contents of a folder with no index file:
Options -Indexes
Deny specific IPs:
deny from 192.168.1.100
Allow specific IPs:
allow from 192.168.1.100
Block everyone:
deny from all
Specify which files should be used as default index files:
DirectoryIndex index.php index.html welcome.html
Redirect a single file:
Redirect /oldpage.html http://example.com/newpage.html
Redirect a directory:
Redirect /oldfolder http://example.com/newfolder
This preserves sub-directory paths and is useful for site migrations.
Step 1: Add to .htaccess in the protected directory:
AuthName "Members Only"
AuthType Basic
AuthUserFile /full/server/path/to/.htpasswd
Require valid-user
Step 2: Create a .htpasswd file with user credentials:
username:encryptedpassword
Use online generators like:
Place the .htpasswd file outside your web root for added security.
Access will trigger a login prompt. Alternatively, credentials can be passed in the URL:
http://username:[email protected]/secure-directory/
⚠️ Caution: This method is insecure as credentials are exposed in the URL.
.htaccess is a versatile and essential tool for managing website functionality and security at the directory level. From simple redirects to access control, it gives developers powerful control without needing access to the core server configuration.