Apache htaccess password authentication, optimisation, and caching

November 30th, 2014

Warning: This post is 9 years old. Some of this information may be out of date.

Here's a few Apache snippets for password authentication, allowing acces via an IP (else requesting password), optimising and caching assets, turning og PHP processing, and more.

Password Authentication

AuthUserFile /usr/local/you/safedir/.htpasswd
AuthGroupFile /dev/null
AuthName EnterPassword
AuthType Basic

require user bob
# or 
require valid-user

Allow from specified IP else Password Authentication

<directory "/home/user/public_html/">
  Options FollowSymLinks
  AllowOverride All
  Order deny,allow
  Deny from all
  Allow from
  Allow from
  AuthType Basic
  AuthName WorkInProgress
  AuthUserFile /etc/apache2/wip.htpasswd
  Require valid-user
  Satisfy any  

Optimisation and Caching

# Deflate (Gzip output). Must have Mod_deflate enabled
<ifmodule mod_deflate.c>
       AddOutputFilterByType DEFLATE text/plain
       AddOutputFilterByType DEFLATE text/xml
       AddOutputFilterByType DEFLATE application/xhtml+xml
       AddOutputFilterByType DEFLATE text/css
       AddOutputFilterByType DEFLATE application/xml
       AddOutputFilterByType DEFLATE application/x-javascript
       AddOutputFilterByType DEFLATE text/html       
       AddOutputFilterByType DEFLATE text/javascript  

<ifmodule mod_expires.c>
        <filesmatch "\.(jpg|jpeg|gif|png|ico)$">
            ExpiresActive on
            ExpiresDefault "access plus 1 year"
        <filesmatch "\.(css|js)$">
            ExpiresActive on
            ExpiresDefault "access plus 7 day"

ExpiresDefault "access plus 10 years"
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000

<filesmatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
    Header set Cache-Control "public"
    Header unset ETag
    FileETag None

### Turn off PHP processing

<directory "/home/site/public_html/site/wp-content">
       php\_admin\_flag engine off
       AllowOverride None
       DirectoryIndex Off
       RewriteEngine On
       RewriteRule .php$ – [F,L]

The rewrite rule simply sends a forbidden and the 'L' makes it the last request.

### Send all to holding page Except for IP's

RewriteEngine on
RewriteCond %{REQUEST_URI} !/holding.html$
RewriteCond %{REMOTE_HOST} !^888.888.888.888
RewriteRule $ /holding.html [R=302,L]

Note: You will also need to allow any images, css and js files that your holding page uses.

### Permanent Redirect All requests to non-www domain to the www:

<virtualhost *:80>
    Servername domain.com
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www.;
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]