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. (For how Apache is wired on a host, see How Apache and Nginx relate.)

Before you start

  • A host that runs Apache (webserver: apache2) - see Configure Apache.

  • SSH or SFTP access to the host - see SSH access. The .htaccess file lives in your application's web root (public_html).

  • For basic authentication, the htpasswd tool from the apache2-utils package, added with os_extra_packages.

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 request reaches Apache from the cache, and the visitor's address arrives in the X-Forwarded-For header. Matching on that header works in both cases:

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.

If it did not work

A 500 on every page of the directory means Apache rejected a line in the file. Read the error with tscli logs web error and remove the last rule you added. A rule with no effect at all is usually in the wrong directory. It can also be that Varnish served the page from its cache, see the note above. See Finding and reading logs, or contact support.