zizhost
Apache

.htaccess basics

Rewrites, redirects, blocking, caching: common .htaccess recipes.


What .htaccess is

A per-directory Apache config file. Drop one in public_html/ and it applies to every request inside.

The fastest way to build one is our .htaccess generator. Below are the recipes it produces, for reference.

Force HTTPS

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

Front controller pattern (PHP frameworks)

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [QSA,L]
</IfModule>

Hide .php extensions

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Block dotfiles and disable directory listings

<FilesMatch "^\.">
  Require all denied
</FilesMatch>
Options -Indexes

Cache headers for static assets

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType text/css              "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType image/png             "access plus 1 year"
</IfModule>

One thing to avoid

Don’t put secrets in .htaccess. It is parsed as text and any future config error could serve it raw. Keep credentials in a PHP file above the document root.