What is .htaccess?
The .htaccess file (Hypertext Access) is a powerful Apache web server configuration file
that allows directory-level customization without modifying the main server configuration. It controls
everything from URL redirects and access control to caching and security headers.
Unlike global server config (httpd.conf), .htaccess files are processed per-request and take effect immediately without server restart—making them ideal for shared hosting environments.
Key Use Cases
Security Hardening
Block directory listings, protect sensitive files, add security headers (HSTS, X-Frame-Options), and hide server version information.
URL Redirects & Rewrites
Implement 301 redirects for SEO, force HTTPS/www, create clean URLs, and manage site migrations.
Password Protection
Restrict access to staging sites or admin areas using HTTP Basic Authentication (.htpasswd).
Performance Optimization
Enable GZIP compression, set browser cache headers (Expires), and improve Core Web Vitals.
Essential Security Configurations
- Disable Directory Indexing:
Options -Indexesprevents file listing exposure. - Protect .htaccess: Deny direct access to configuration files.
- X-Frame-Options: Prevents clickjacking attacks.
- X-Content-Type-Options:
nosniffstops MIME-type guessing. - HSTS: Forces HTTPS for all future visits (use carefully).
Performance Tips
- GZIP Compression: Reduces file sizes by 60-80% for HTML, CSS, JS.
- Expires Headers: Set far-future expiration for static assets.
- Minimize Overuse: Each rule adds per-request processing.
Understanding .htpasswd
The .htpasswd file stores encrypted passwords for HTTP Basic Auth:
- Encryption: Passwords are hashed (bcrypt, MD5). Never plain text.
- Placement: Store ABOVE public_html for security.
- Absolute Paths: AuthUserFile requires full server path.
Common Mistakes
- Infinite Redirect Loops: HTTPS + www redirects must check current state.
- Forgetting RewriteEngine On: All mod_rewrite rules require this.
- Syntax Errors: Any typo causes 500 Internal Server Error.



