Apache .htaccess Basics: Rewrites, Redirects, and Access Control

.htaccess files let you override Apache configuration on a per-directory basis without touching the main server config — essential on shared hosting where you don’t have access to the main config at all.

# Redirect old URL to new
Redirect 301 /old-page.html /new-page.html

# Rewrite pretty URLs to a query string (common in PHP frameworks)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

# Password-protect a directory
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/www/.htpasswd
Require valid-user

# Block access to sensitive files
<FilesMatch "\.(env|log|sql)$">
    Require all denied
</FilesMatch>

The Performance Trade-off

Apache checks for .htaccess files on every single request by walking up the directory tree — a real, measurable performance cost. If you have server config access, putting these same directives directly in the virtual host config with AllowOverride None is meaningfully faster.