Using Apache Memory Cache

Apache has its own memory cache module mod_mem_cache which can be used to cache content similar to memcached. The following directives configure Apache to use 1GB of memory and will cache up to 1000 objects, each between 1 byte and 1 megabyte.

<IfModule mod_mem_cache.c>
  Cache Enable mem /
  MCacheSize 1074741824
  MCacheMaxObjectCount 1000
  MCacheMaxObjectSize 1048576

Usual Required Modules

# Proxy needed by default on OSX
# DAV needed by default on OSX
# Status needed by default on OSX

Remove Directory Listing


Options Indexes FollowSymLinks MultiViews

and remove Indexes from the options list.

Allow and Deny Network

Every directory can be protected with Allow and Deny. The following example denies access to the root path / to anybody except the local network

<Directory />
       Order deny,allow
       Allow from
       Deny from all

The Order is important - it says to first deny, which resolves to Deny from all and after that to allow which resolves to Allow from

Reverse Proxy with Virtual Host

Apache can be configured as a reverse proxy in order to pass traffic to a backend. For example, the following directives:

<VirtualHost *:80>
       ProxyRequests Off
       ProxyPreserveHost On
       ProxyPass / connectiontimeout=300 timeout=300
       ProxyPassReverse /
       ServerAlias *
       ErrorLog ${APACHE_LOG_DIR}/error.log
       LogLevel warn
       CustomLog ${APACHE_LOG_DIR}/access.log combined

will redirect all traffic for and any sub-domain, such as to the host Additionally, it specifies that connections will timeout in 300s. As long as:

<VirtualHost *:80>

is specified, then you can have any number of websites to be proxied to their respective backends.

Block Bad Bots

On Debian-like systems, a global rule can be set to block bad bots. In order to do so create a file: /etc/apache2/conf.d/blockbots.conf containing the bad_bots configuration.

You must also enable the setenvif module with:

a2enmod setenvif

Create WebDAV Share

The following directive will share /var/www/webserver/share through WebDAV:

        <Directory /var/www/webserver/share>
                DAV On
                AuthType Digest
                AuthName "share"
                AuthDigestDomain /
                AuthDigestProvider file
                AuthUserFile /etc/apache2/.htpasswd
                <LimitExcept PROPFIND>
                    Require valid-user

It seems that Directory is prefered instead of Location; the latter leading sometimes to System Error 67 meaning that the network path could not be found.

The authentication mechanism to use for maximum compatibility is Digest and username and password pairs can be generated using the htdigest command line utility. For this example:

htdigest -c /etc/apache2/.htpasswd share username

which will prompt for a password.

If you have been trying for a while to access the DAV share from Windows and are prompted for the username and password over and over again even if you entered the correct information, you may want to run in Windows on a command prompt:

net stop WebClient
net start WebClient

in order to restart the web-client thereby resetting WebDAV caches and fixing the username and password prompt loop.

Set Expiration for Resources

After enabling mod_expires with:

a2enmod expires

after which an optimized configuration can be added as a file under /etc/apache/conf.d/ in order to set the expiration time for resources.

Apache Logs Statistics Through using The Shell

We use zcat in combination with the -f flag to read compressed and uncompressed files. The commands assume that your current working directory is in the apache log directory. The commands also assume that the files are named access.log* which may be different on other systems (ie: access_log).

Get Number of Unique Visitors

zcat -f access.log* | awk '{print $1}' | sort -u | wc -l

Get Number of Unique Returning Visitors

zcat -f access.log* | awk '{print $1}' | sort | uniq -c -d | sort -n -k 1

Apache Image Hot-Link Protection

The idea of preventing people from hot-linking images on your website is contradictory in itself: if you are serving content, then why prevent people from using the content you provide? You can instead shut your website down and keep the content to yourself.

Nevertheless, some people chose to do this, and one way to prevent hot-linking is to branch on the referrer (typo intentional in the example below) and deny any access to images when the referrer is not your website. In the example, we assume that and are the accepted domains used as referrer to your images and any other referrer, except a blank referrer (last rule) is denied the connection:

SetEnvIfNoCase Referer "^" locally_linked=1
SetEnvIfNoCase Referer "^$" locally_linked=1
SetEnvIfNoCase Referer "^" locally_linked=1
SetEnvIfNoCase Referer "^$" locally_linked=1
SetEnvIfNoCase Referer "^$" locally_linked=1
<FilesMatch "\.(gif|png|jpe?g)$">
Order Allow,Deny
Allow from env=locally_linked

Note that branching on referrers is a very bad idea, given upstream caches that may manipulate headers as well as the possibility to circumvent this protection easily by sending a different referrer (your domain) along with the request. Bad, bad idea.

Permanently Redirecting pages

The best way to permanently redirect surfers to a different website is to RedirectMatch with the permanent option. This will ensure that the 301 (permanently moved) will be sent before redirecting.

Suppose you have a virtual host configuration for the domain

<VirtualHost *:80>
  DocumentRoot  /var/www/
  <Directory /var/www/
    Order allow,deny
    Allow from all

and that you want to redirect to You would then add another virtual host that will perform the redirection:

<VirtualHost *:80>
  RedirectMatch permanent ^/(.*)$1

Migrating Website Domain

In this example, we want to move to We already have a virtual host in-place to handle and we need to redirect every page from as well as any sub-domains to In order to do that, we modify the old virtual-host for

<VirtualHost *:80>
        ServerAlias   *
        RewriteEngine on
        RewriteCond   %{HTTPS}s    ^..(s?)
        RewriteRule   ^            -                                 [E=PROTO:http%1]
        RewriteCond   %{HTTP_HOST} !^\w+\.newsite\.org$              [NC]
        RewriteCond   %{HTTP_HOST} ^(\w+)\.\w+\..+                   [NC]
        RewriteRule   ^/?(.*)      %{ENV:PROTO}://%1.$1 [R=301,L]
        RewriteCond   %{HTTP_HOST} somesite\.net
        RewriteRule   ^/?(.*)      %{ENV:PROTO}://$1     [R=301,L]

this will match both protocols, HTTP and HTTPs (matching the last s), it will also match any sub-domains and redirect everything to

Disabling Timeouts for Long-Running Services

When using a web-server for live streams or software repositories (git, svn, etc…) it is sometimes useful to disable timeouts. This can be done in apache using the following directives:

<IfModule reqtimeout_module>
    RequestReadTimeout header=0 body=0
LimitRequestBody 0

Make Apache Case-Insensitive

When migrating documents from case-insensitive filesystems to a server with Apache and a case-sensitive system, some links may appear broken and inaccessible. In order to resolve this, enable the speling (note the lack of double-l) module with:

a2enmod speling

and then either in an .htaccess, Directory directive or globally add the setting:

CheckSpelling on

Configure Zend OpCache

To increase the amount of memory alloted to the Zend OpCache found in newer PHP variants, edit the file /etc/php5/apache2/conf.d/05-opcache.ini. It should contain something like the following:

; configuration for php ZendOpcache module
; priority=05

and then after that line add the following options:


Redirect to HTTPs and then Authenticate

Suppose you have a /support alias where clients should be able to access some protected data by authenticating first using basic authentication. In this case, the password may travel over the wire unencrypted such that we need to first redirect through HTTPs and then provide authentication.

In the example below a /support alias is created that is protected by basic authentication through PAM. By using the 403 error document we can redirect to the HTTPs version of the website site.tld.

Alias /support /usr/share/support
<Directory /opt/support>
  Options FollowSymLinks MultiViews
  AllowOverride All
  SSLOptions +StrictRequire
  ErrorDocument 403 https://site.tld/support
  AuthType Basic
  AuthName "Restricted Area"
  AuthBasicProvider external
  AuthExternal pwauth
  GroupExternal unixgroup
  Require valid-user

The reason for this hack is that authentication takes precedence such that using mod_rewrite to create a redirect would not work. As such, the setup now generates a 403 error when the HTTP version of the website is requested, which in turn redirects to the HTTPs version where the authentication takes place over HTTPs.

Enable HSTS

If a website accepts a connection through HTTP and then redirects to HTTPS, there is a small window of opportunity where the client talks to the server without encryption that can be abused with a MITM attack.

First enable the headers module:

a2enmod headers

To enable HSTS, edit the SSL virtual host version of your website and add the following stanza:

Header always set Strict-Transport-Security "max-age=31556926; includeSubdomains;"

this will tell browsers to use the HTTPS version of the website without loading the HTTP version first.

The age in the example is set to one year and the includeSubdomains option will enable HSTS for any subdomains as well.

Enforce Strong Cryptography

When using Apache SSL, the following directives should be added in order to use strong cryptography:

SSLProtocol all -SSLv2 -SSLv3
SSLHonorCipherOrder on
SSLCompression off
SSLSessionTickets off

the settings will disable SSLv2 and SSLv3 as well as enable most of the elliptic-curve cryptography.

Optionally, given a non self-signed certificate, SSL stapling can be used for apache above 2.3.3:

SSLUseStapling on
SSLStaplingResponderTimeout 5
SSLStaplingReturnResponderErrors off
SSLStaplingCache shmcb:/var/run/ocsp(128000) 

Return 404 for Default Virtual Host

Create a virtual host file or create a virtual host using the following configuration:

<VirtualHost *:80>
	Redirect 404 /

The effect is that if a visitor attempts to access the server IP directly, the default virtual host will return a 404 error.

Calculate the Optimal Maximum Number of Concurrent Connections

To calculate the MaxClients value for Apache, you first need to get the Resident Set Size (RSS) of an Apache process. In order to do this, under Linux, you can issue:

ps -ylC apache2 --sort:rss

otherwise, the top utility may work as well by watching the SIZE or RSS value.

The formula to calculate the value that should be passed to MaxClients in the Apache configuration is:

\text{MaxClients} &=& \frac{(\text{Total Memory}\mbox{ }GB) * 1024 - \text{Memory for Other Processes}\mbox{ }MB}{\text{Resident Set Size (RSS)}\mbox{ }MB} \\

For instance, assuming a server with a total of 8GB of RAM, leaving 1GB over to other processes, and with an Apache RSS of 100MB the calculation would become:

\text{MaxClients} &=& \frac{8GB * 1024 - 1024}{100MB} \\
&\approx& 71 

fuss/apache.txt · Last modified: 2017/02/22 18:30 (external edit)

Access website using Tor Access website using i2p

For the copyright, license, warranty and privacy terms for the usage of this website please see the license, privacy and plagiarism pages.