Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Linux

.htaccess on your own Apache server: keep, move or drop

On your own Apache server you decide if .htaccess is read at all: set AllowOverride, move rules into the vhost, keep the useful ones and debug what breaks.

CloudSat teamNovember 18, 20267 min read
Abstract illustration of small paper notes pinned inside nested folders, with one master scroll gathering them into a single panel
On this pageWhat Apache does with a .htaccess file

On shared hosting, a .htaccess file is the only lever you have: you cannot touch the server configuration, so redirects, password protection and PHP settings go into a file next to your pages. On your own server you hold the main configuration, and Apache's documentation is blunt about it: if you can edit the main configuration file, put your configuration there. That turns .htaccess from a necessity into a choice you make per site.

What Apache does with a .htaccess file

A .htaccess file (the name is set by AccessFileName) holds configuration for the directory it sits in and everything below it. Apache does not load it at startup. It reads it during requests, and when overrides are allowed it looks for one in every directory on the path. Apache's own example: a request for a file in /www/htdocs/example, with overrides enabled from /, means checking /.htaccess, /www/.htaccess, /www/htdocs/.htaccess and /www/htdocs/example/.htaccess, four extra file system lookups per request even if none of the files exist.

When AllowOverride and AllowOverrideList are both None, which is the default, Apache does not even look. Debian and Ubuntu set exactly that for /var/www in apache2.conf, which is why a WordPress site copied from shared hosting often loses its pretty permalinks on a fresh VPS.

There is also a security argument. A .htaccess file in the document root is server configuration that the web application can rewrite. If a compromised plugin can write files, it can add redirects or change handlers, a pattern behind many sites that end up flagged by browser blocklists.

Pick a setup per site

Setup Directives in the <Directory> block Use it when
Off AllowOverride None You manage the virtual host yourself (the best default)
Narrow AllowOverride None plus AllowOverrideList Redirect RedirectMatch Editors maintain redirects without root access
By class For example AllowOverride FileInfo AuthConfig An application writes its own rules and you cannot avoid it

AllowOverride All accepts any directive valid in .htaccess context. It is what shared hosts use, and it is rarely what you want on a server where you could write the rules yourself. With the narrow setup, any directive outside the list causes an internal server error, so mistakes are loud.

If you do allow classes, this is what each one opens:

Class Directives it allows
AuthConfig Require, AuthType, AuthName, AuthUserFile
FileInfo RewriteEngine, RewriteCond, RewriteRule, Redirect, RedirectMatch, Header, ErrorDocument, SetEnvIf
Indexes DirectoryIndex, IndexOptions, and the mod_expires directives such as ExpiresByType
Options Options and XBitHack, optionally restricted with Options= and a list
Limit The legacy Order, Allow and Deny; use Require instead

Move the rules into the virtual host

The Apache documentation states that a directive in .htaccess inside a directory is completely equivalent to the same directive in a <Directory> section for that path. mod_rewrite treats both as per-directory context, so rewrite rules usually move across unchanged: in that context a pattern never starts with a slash, whichever of the two holds it.

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example

    <Directory /var/www/example>
        AllowOverride None
        Options FollowSymLinks
        Require all granted

        # Moved from /var/www/example/.htaccess
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]
    </Directory>
</VirtualHost>

Repeat the block in every virtual host that serves the site, including the HTTPS one. Options FollowSymLinks is there on purpose: per-directory rewriting needs FollowSymLinks or SymLinksIfOwnerMatch, and leaving Indexes out turns directory listings off. Then check and reload:

sudo a2enmod rewrite
sudo apachectl configtest && sudo systemctl reload apache2

Once the site works, move the old .htaccess out of the web root so nobody edits a file that no longer does anything.

Rules worth keeping, wherever they live

Hide dotfiles and directory listings

Directory listings expose backups and forgotten files, and dot paths such as .env or .git/ hold secrets. One mod_alias rule answers 404 for every dot path except the ACME challenge directory that certificate renewals use:

Options -Indexes
RedirectMatch 404 "/\.(?!well-known/)"

Restrict an admin path

In the virtual host, a <Location> block limits an admin area to your own addresses. <Location> is not allowed in .htaccess; there you would put a Require line in a file inside the protected directory.

<Location "/admin">
    Require ip 198.51.100.0/24 2001:db8::/32
</Location>

Behind a proxy or CDN, Apache sees the proxy's address unless mod_remoteip is configured, so check that first.

Caching and security headers

ExpiresActive On
ExpiresByType image/webp "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"

Enable the modules with sudo a2enmod expires headers instead of wrapping these lines in <IfModule>. A missing module should fail the config test, not silently drop your headers.

Error pages and redirects

ErrorDocument 404 /errors/404.html gives visitors your own page. Redirects deserve more care than a one-liner; our guide to 301 redirects in WordPress covers status codes, Apache and Nginx rules, and testing for chains.

PHP settings depend on how PHP runs

php_value and php_flag in .htaccess only work when PHP runs as an Apache module (mod_php), and they need AllowOverride Options or All. Many current setups run PHP-FPM through mod_proxy_fcgi instead. There, a php_value line is an unknown directive and the whole directory answers 500. Check which one you have:

apachectl -M 2>/dev/null | grep -E 'php|proxy_fcgi'

With PHP-FPM, use a .user.ini file in the directory or the pool configuration. PHP reads .user.ini only under CGI and FastCGI, ignores settings that only php.ini may set, and rereads the file every 300 seconds by default:

; /var/www/example/.user.ini
upload_max_filesize = 64M
post_max_size = 64M

The pool file applies to every site in that pool, and php_admin_value settings there cannot be overridden by the application. Reload php8.3-fpm (or your version) after editing it:

; /etc/php/8.3/fpm/pool.d/www.conf
php_admin_value[upload_max_filesize] = 64M
php_admin_value[post_max_size] = 64M

When a rule does nothing, or breaks everything

  • Nothing happens. The file is probably not read. Apache's documentation suggests a quick test: put a line of garbage in it. If the site does not answer 500, AllowOverride None is in effect, or the module the rule needs is disabled.
  • Everything answers 500. Read the error log. Apache names the file and the problem, with messages such as DirectoryIndex not allowed here (the class is not allowed) or RewriteCond: bad flag delimiters (a syntax error).
  • The config test passed. apachectl configtest only parses files loaded at startup, so it never sees .htaccess. That alone is a reason to keep rules in the virtual host, where a typo is caught before reload instead of by visitors.

For rewrite rules that match the wrong thing, turn on tracing in the virtual host, reproduce the request and read the log:

# Add to the vhost temporarily: LogLevel alert rewrite:trace3
sudo systemctl reload apache2
curl -sI https://example.com/old-page
sudo grep 'rewrite:' /var/log/apache2/error.log | tail -n 20

Remove the LogLevel line when you are done. The documentation warns that trace levels above trace2 slow Apache down dramatically.

Leaving Apache later

Nginx and Caddy read no per-directory files at all. Every rule lives in the server configuration and takes effect on reload, so rules already gathered in one virtual host are much easier to translate. The front-controller block above becomes try_files $uri $uri/ /index.php?$args; in an Nginx location /, and Caddy's php_fastcgi directive already includes the equivalent try_files {path} {path}/index.php index.php. For choosing between the servers, see Apache, Nginx or OpenLiteSpeed for WordPress.

On CloudSat, the LAMP stack and Apache HTTP Server deploy as one-click apps, with root access to every virtual host file.

FAQ

Will turning off .htaccess break WordPress?

Only if you skip the move. Permalinks depend on the rewrite block WordPress writes to .htaccess. Copy it into the site's <Directory> block, reload, test a few post URLs, then set AllowOverride None. If WordPress cannot write the file, Settings > Permalinks shows the rules for you to add by hand.

Can I allow .htaccess for one directory only?

Yes. Keep AllowOverride None for the site and add a second <Directory> block for the one path that needs it, with only the classes or the AllowOverrideList entries it uses.

Why does my .htaccess work on shared hosting but not on my VPS?

Shared hosts usually allow overrides and load mod_rewrite. A fresh Debian or Ubuntu server does neither for /var/www. Enable the module, then move the rules into the virtual host.

Is the performance cost worth worrying about?

Each request costs extra file system lookups, more with deep directory trees, even when no file exists. On a quiet site you will not notice. The stronger reasons to switch are loud configuration errors and a web application that can no longer rewrite your server rules.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.