Apache 2.4 · practical reference

What .htaccess is—and when not to use it

.htaccess is a per-directory Apache configuration file. It is useful when hosting does not provide access to the main server configuration, but it is not a universal configuration file for Nginx, IIS or every hosting stack.

An .htaccess file open in an editor
Back up the current file and confirm that the public server is Apache before changing it.

Before editing

  • identify Apache and the directory whose requests the file controls;
  • save the current file and have file-manager or SSH access for rollback;
  • check which directives the host permits through AllowOverride;
  • change one rule at a time and test both the target URL and unrelated pages.

With server-administration access, Apache recommends putting configuration in the main server files: it is clearer and avoids per-request directory lookups.

Common safe uses

TaskCurrent approachImportant limit
Default documentDirectoryIndex index.html index.phpThe directive must be allowed by the host.
Custom 404 pageErrorDocument 404 /404.htmlThe error page itself must return and render correctly.
Canonical redirectmod_rewrite with a precise host/protocol conditionTest query strings, paths, proxy/CDN headers and redirect loops.
Access restrictionApache 2.4 Require directivesOld Order, Allow and Deny examples are deprecated.
Protect sensitive files<FilesMatch> with Require all deniedSecrets should not be stored inside the public document root.

A redirect example

RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

This is an illustration, not a copy-and-paste rule for every server. A reverse proxy or CDN can change how HTTPS and the original host are reported. Test with a temporary redirect when the infrastructure is uncertain, then use the permanent status after verification.

What not to solve with copied snippets

  • do not redirect mobile users by User-Agent to a separate folder—use responsive design unless a documented architecture requires otherwise;
  • do not treat blocking a few bot names as security; User-Agent is easy to spoof;
  • do not force downloads by assigning arbitrary MIME types without checking security and user expectations;
  • do not enable compression, caching and security headers in several layers at once.

Verification and rollback

  1. Check Apache configuration or the hosting error log.
  2. Request affected URLs and inspect status, Location and response headers.
  3. Test forms, static files, the home page and an internal page.
  4. If a 500 error or loop appears, restore the saved file immediately.

Comments


You can leave a comment, ask a question, or share your opinion. Feedback helps us improve these materials.