Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 30 ยท Apache Configuration

.htaccess, Directory Rules and AllowOverride

Understand .htaccess files and per-directory rules in Apache: AllowOverride, Require access control, Options, the performance cost, and moving rules into the main config.

If you have ever uploaded a website to shared hosting, you have probably edited a file called .htaccess. It is a small text file, dropped into any directory, that changes how Apache serves that directory and everything below it, with no root access and no restart. That convenience made it famous, and it is also the reason Apache has a reputation for being slower than nginx, which has no such thing.

In this lesson you will learn what a .htaccess file can and cannot do, how AllowOverride decides which directives are allowed, how to control access with Require, what the Options directive switches on and off, why per-directory files cost performance, and how to move their rules into the main configuration. It builds on the container rules from Apache httpd Configuration.

What .htaccess does

A .htaccess file contains ordinary Apache directives. Instead of editing httpd.conf, you write them next to your content:

APACHE
# /var/www/site/blog/.htaccess
ErrorDocument 404 /blog/missing.html
Options -Indexes
Header set X-Area "blog"

The file name comes from the AccessFileName directive (default .htaccess). The rules apply to the directory containing the file and all subdirectories. Apache re-reads these files on every request; there is no cache and no reload command, so your edit is live the moment you save it. That is wonderful for a hosting provider whose customers should not touch the main config, and risky for everyone else: a typo in one file turns every page below it into a "500 Internal Server Error" instantly.

AllowOverride decides what is permitted

Apache only looks at .htaccess files in directories where the main config says it may. That is the job of AllowOverride, set inside a <Directory> block:

APACHE
<Directory "/var/www">
    AllowOverride None
</Directory>

<Directory "/var/www/site">
    AllowOverride FileInfo AuthConfig
</Directory>

None means "do not even look for a .htaccess file". All allows everything. Between them are categories of directives:

Category What it lets .htaccess change (examples)
AuthConfig Authentication and access: AuthType, Require, AuthUserFile
FileInfo Document types and URL handling: RewriteRule, ErrorDocument, Header, AddType
Indexes Directory listing settings: DirectoryIndex, IndexOptions
Limit Host access directives from older configs: Order, Allow, Deny
Options The Options directive (can be narrowed, Options=Indexes,MultiViews)

Since Apache 2.4 the default is AllowOverride None, so a fresh install ignores .htaccess until you enable it. A directive from a category that is not allowed does not get silently ignored: Apache answers every request in that directory with a 500 error and logs "not allowed here" in the error log. If a hosting customer reports "my site broke after I added Options -Indexes", this is the first thing to check.

Controlling access with Require

Require is the modern access-control directive from the mod_authz_* modules. Use it in <Directory>, <Location>, <Files> or .htaccess (the last one needs AuthConfig).

APACHE
Require all granted                 # anyone
Require all denied                  # nobody
Require ip 192.0.2.0/24 10.0.0.5    # these addresses only
Require host example.com            # clients whose reverse DNS ends in example.com
Require valid-user                  # any logged-in user (needs AuthType)

Several Require lines are combined with OR by default: any one matching is enough. To demand that all conditions hold, group them:

APACHE
<RequireAll>
    Require ip 10.0.0.0/8
    Require valid-user
    Require not ip 10.0.0.99
</RequireAll>

Do not mix the old Order, Allow from and Deny from directives with Require. They belong to Apache 2.2, still load through the compatibility module mod_access_compat, and combining the two styles produces confusing results. A password-protected area uses the same machinery:

APACHE
AuthType Basic
AuthName "Staff only"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

The password file is created with htpasswd -c /etc/apache2/.htpasswd ada, and should live outside any DocumentRoot. Basic authentication sends credentials with every request, so only use it over HTTPS (more in Access Control and Rate Limiting).

Options switches optional server features for a directory. The ones you will meet most:

  • Indexes: when a directory has no index file (index.html), show an automatically generated file listing. Convenient for a download folder, dangerous almost everywhere else because it exposes every file name. Use -Indexes as the safe default.
  • FollowSymLinks: let Apache follow symbolic links inside the directory. Most setups need it; SymLinksIfOwnerMatch is a safer alternative that follows a link only if the link and its target have the same owner, at the cost of extra checks.
  • MultiViews: content negotiation that guesses a file extension (/about serves about.html). It surprises people and interferes with rewrites; leave it off unless you want it.
  • ExecCGI: allow CGI scripts to run.

A bare Options Indexes FollowSymLinks replaces the earlier setting entirely. Prefix each name with + or - to add or remove from what was inherited, and never mix the two styles in one directive:

APACHE
Options -Indexes +FollowSymLinks

Why .htaccess costs performance

Apache cannot know in advance whether a .htaccess exists in a directory. For a request to /var/www/site/blog/2024/post.html, with overrides enabled everywhere, it has to try to open .htaccess in /, /var, /var/www, /var/www/site, /var/www/site/blog and /var/www/site/blog/2024, on every request, then parse each file it finds. Those are extra system calls on the hottest path of the server, and the parsing work repeats for every single hit. This is the main architectural difference described in Nginx vs Apache: nginx reads its configuration once, at start or reload.

The cost shrinks when you disable overrides high in the tree: with AllowOverride None at / and /var/www, Apache skips those lookups and only checks below the directory that allows them. It disappears entirely when you move the rules into the main config, which Apache reads once.

The simulation below walks a request path from the root down. It checks AllowOverride at every level, counts the file lookups, collects the directives and applies them in order. Try changing the overrides table to see lookups and errors change.

JS Stand-in: collecting .htaccess layers up the path

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the numbers: with overrides allowed everywhere, a request deep in the tree costs six lookups. With overrides allowed only from /var/www/site down, it costs two. With AllowOverride None, it costs none, and the files are not read at all, which is also why leaving old .htaccess files behind is harmless once you have turned the feature off.

Moving .htaccess rules into the main config

If you control the server, put the rules in the main configuration and turn overrides off. A typical file such as:

APACHE
# .htaccess
Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Header set X-Content-Type-Options nosniff

becomes, inside the site's virtual host:

APACHE
<Directory "/var/www/site/public">
    AllowOverride None
    Require all granted
    Options -Indexes

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

    Header set X-Content-Type-Options nosniff
</Directory>

The rules work the same way (inside a <Directory> block, RewriteRule patterns are matched against the path without the leading slash, exactly as in .htaccess), but Apache parses them once at startup. Add AllowOverride None so a stray file cannot change behavior behind your back. Apache has to be reloaded for changes to apply. If the apps you deploy ship a .htaccess (many PHP frameworks do), copy its contents into your vhost and disable overrides for that directory.

Keep .htaccess where it really belongs: shared hosting, or an application whose owners must change rules without server access. For the rewrite syntax see Redirects and Rewrites.

Protect the files themselves. The default Debian and RHEL configs deny requests for names that start with .ht using <FilesMatch "^\.ht">Require all denied</FilesMatch>, so nobody can download your .htaccess or .htpasswd. Keep that rule.

A quick comparison with nginx

Nginx has no per-directory files. Every rule lives in the main configuration and takes effect on reload. The equivalent of Require ip is allow and deny, and Options -Indexes is simply the absence of autoindex on. That is faster and more predictable, but it means no self-service for customers. You will find the nginx counterparts in Location Blocks and Matching Order and Access Control and Rate Limiting.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A customer adds Options -Indexes to .htaccess and every page in that directory returns a 500 error. The error log says the directive is not allowed here. What is the most likely cause?

    A directive from a category that AllowOverride does not permit makes Apache fail the request with a 500. Allowing the Options category, or moving the directive into the main config, fixes it.
  2. 2. How often does Apache read a .htaccess file?

    Apache checks for and re-reads per-directory files on each request, which makes edits instant but costs performance.
  3. 3. Which line makes a directory require both an internal IP address and a logged-in user?

    Separate Require lines are combined with OR. A RequireAll container demands that every inner condition is true.
  4. 4. What is the best way to get the speed back when you control the server?

    Rules in the main config are parsed once at startup, and AllowOverride None stops the per-request lookups completely.

Summary

  • A .htaccess file applies Apache directives to its directory tree and is re-read on every request.
  • AllowOverride (default None in 2.4) decides which categories of directives are honored; a forbidden directive causes a 500 error.
  • Require controls access; separate lines mean OR, <RequireAll> means AND; do not mix it with the old Order/Allow/Deny.
  • Options -Indexes hides directory listings; use + and - forms to avoid wiping inherited options.
  • Per-directory files cost lookups on every request; move rules into <Directory> blocks and set AllowOverride None when you can.

Next: Redirects and Rewrites.