BlogWeb Servers

The Apache .htaccess File: A Practical Guide

Web Servers·11 min read·By the TorixPulse Team

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:

apache
<Directory /var/www/example/public>
    AllowOverride All
    Require all granted
</Directory>
On servers you control, .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

apache
# 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:

apache
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

Access control

apache
# 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-user

Create the password file with htpasswd -c /var/www/.htpasswd admin.

Protect sensitive files

apache
# Deny access to dotfiles and config
<FilesMatch "(^\.|\.(env|ini|log|sql|bak)$)">
    Require all denied
</FilesMatch>

Caching and compression

apache
<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

apache
ErrorDocument 404 /errors/404.html
ErrorDocument 503 /errors/maintenance.html

Debugging tips

  • A syntax error in .htaccess causes a 500 for the whole directory — check error.log.
  • Rules are processed top to bottom; order matters, especially with [L].
  • Confirm the needed modules (mod_rewrite, mod_headers) are enabled.
Monitor it with TorixPulseA bad .htaccess rule can take a site down instantly — get alerted if it does.
Start free