The Apache .htaccess File: A Practical Guide
The .htaccess file is Apache's per-directory configuration file. Drop one in a folder and its rules apply to that folder and everything below it — without touching the main server config or restarting Apache. That makes it the workhorse of shared hosting, where you often can't edit the global config.
Enabling .htaccess
Apache only reads .htaccess if AllowOverride permits it in the main config:
<Directory /var/www/example/public>
AllowOverride All
Require all granted
</Directory>.htaccess is slower than main-config rules (Apache checks for the file on every request). Use it for flexibility on shared hosting; prefer the VirtualHost when you have access.Redirects
# Redirect a single old URL
Redirect 301 /old-page /new-page
# Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Force www (or drop it)
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]Pretty URLs with mod_rewrite
The classic front-controller pattern — route everything that isn't a real file to index.php:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]Access control
# Block one IP, allow the rest
<RequireAll>
Require all granted
Require not ip 203.0.113.42
</RequireAll>
# Password-protect a directory
AuthType Basic
AuthName "Restricted"
AuthUserFile /var/www/.htpasswd
Require valid-userCreate the password file with htpasswd -c /var/www/.htpasswd admin.
Protect sensitive files
# Deny access to dotfiles and config
<FilesMatch "(^\.|\.(env|ini|log|sql|bak)$)">
Require all denied
</FilesMatch>Caching and compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
</IfModule>Custom error pages
ErrorDocument 404 /errors/404.html
ErrorDocument 503 /errors/maintenance.htmlDebugging tips
- A syntax error in
.htaccesscauses a 500 for the whole directory — checkerror.log. - Rules are processed top to bottom; order matters, especially with
[L]. - Confirm the needed modules (
mod_rewrite,mod_headers) are enabled.