The .htaccess file is a powerful configuration file for Apache web servers. It allows you to control various aspects of your website without modifying the main server configuration.
What Is .htaccess?
The .htaccess (hypertext access) file is a directory-level configuration file. When placed in a directory, its rules apply to that directory and all subdirectories. The file name starts with a dot, making it a hidden file on Unix-based systems.
Where to Place .htaccess
The most common location is your website root (public_html). You can also place additional .htaccess files in subdirectories for directory-specific rules.
Common Directives
URL Redirects:
Redirect 301 /old-page https://yourdomain.com/new-page
URL Rewriting (requires mod_rewrite):
RewriteEngine On
RewriteRule ^about$ /about-us.html [L]
Force HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Custom Error Pages:
ErrorDocument 404 /errors/not-found.html
ErrorDocument 500 /errors/server-error.html
Directory Listing:
# Disable directory listing
Options -Indexes
Password Protection:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
Security Headers:
Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-XSS-Protection "1; mode=block"
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Caching:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
PHP Settings:
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
Block IP Addresses:
Deny from 192.168.1.100
Deny from 10.0.0.0/8
Troubleshooting
If your .htaccess changes cause a 500 error:
1. Check for syntax errors in the file.
2. Make sure required modules are enabled (mod_rewrite, mod_headers).
3. Comment out lines one by one to find the problematic directive.
4. Ensure directives are enclosed in proper <IfModule> blocks.
Important Notes
- Always back up your .htaccess file before editing.
- A syntax error in .htaccess will cause a 500 Internal Server Error for your entire site.
- Changes take effect immediately with no server restart required.
- The file must be saved as plain text with Unix line endings.