.htaccess Guide
.htaccess Configuration Guide
This guide covers common .htaccess configurations and examples for Apache web servers.
Common Use Cases
URL Rewriting
# Redirect all requests to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Remove .html extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
Error Pages
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
Directory Protection
# Password protect a directory
AuthType Basic
AuthName "Restricted Access"
AuthUserFile /path/to/.htpasswd
Require valid-user
PHP Settings
# Set PHP values
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
Security Headers
# Add security headers
Header set X-XSS-Protection "1; mode=block"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set Referrer-Policy "strict-origin-when-cross-origin"
Performance Optimization
Enable Caching
# Cache static assets
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
Enable Compression
# Enable GZIP compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
Common Issues and Solutions
The most common cause is incorrect file permissions. Make sure:
- Directory permissions are set to 755
- File permissions are set to 644
- .htaccess file is readable by Apache
Usually caused by syntax errors in .htaccess. Check:
- Apache error logs
- Syntax of RewriteRules
- Module availability (mod_rewrite, mod_headers, etc.)
Additional Resources
Info
Remember to always backup your .htaccess file before making changes, and test the changes in a development environment first.
Tip
You can use the Apache .htaccess Tester to validate your rules before applying them.