How to use .htaccess overrides

Use per-directory .htaccess rules with Apache on TurboStack.

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.)

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 and generate a password file.

On a host without Varnish:

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):

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:

<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.