# How to use .htaccess overrides

When your host runs Apache, you can use per-directory `.htaccess` files in your web root for rewrites,
access control and headers. Apache reads them on each request, so changes take effect without a
reload. (Apache runs as the backend behind Nginx - see [Run Apache behind Nginx](apache-behind-nginx.md).)

> [!NOTE]
> For blocking abusive traffic, prefer [TurboShield](../turboshield/what-is.md) and the
> [Firewall](../firewall/what-is.md). Use `.htaccess` for application-level rules.

## Restrict by IP with basic authentication

Ask visitors to log in, but let trusted IP addresses through without a prompt. Put the block at the
**top** of your `.htaccess`. First install `htpasswd` (the `apache2-utils` package) via
[`os_extra_packages`](../../platform/hosts/advanced/install-packages.md) and generate a password file.

On a host **without Varnish**:

```apache
AuthType Basic
AuthName "Restricted content"
AuthUserFile /var/www/prod/apache2/.htpasswd
Require ip 203.0.113.10
Require valid-user
```

On a host **with Varnish**, the visitor's IP arrives in the `X-Forwarded-For` header, so match on
that instead (a plain `Require ip` will not match behind Varnish):

```apache
AuthType Basic
AuthName "Restricted content"
AuthUserFile /var/www/prod/apache2/.htpasswd
SetEnvIf X-Forwarded-For 203.0.113.10 AllowIP
Require env AllowIP
Require valid-user
```

## Block an abusive bot

If a single bot drives up load (for example Bytespider), deny it by user agent:

```apache
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} Bytespider [NC]
    RewriteRule .* - [F]
</IfModule>
```

## Verify

Reload the affected pages and confirm the rule works - for example you are prompted to log in (or let
through from a trusted IP), or the blocked bot receives `403 Forbidden`.

> [!WARNING]
> A syntax error in `.htaccess` can return `500` errors for the whole directory. Change one rule at a
> time and test. If you are unsure, [contact support](../../platform/support.md).

## Related

- [Run Apache behind Nginx](apache-behind-nginx.md)
- [Configure Apache](configure.md)
- [Installing extra OS packages](../../platform/hosts/advanced/install-packages.md)
- [TurboShield](../turboshield/what-is.md)
