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 86.129.133.186
Allow from 86.188.161.66
AuthType Basic
AuthName WorkInProgress
AuthUserFile /etc/apache2/wip.htpasswd
Require valid-user
Satisfy any
</directory>
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>
<ifmodule mod_expires.c>
<filesmatch "\.(jpg|jpeg|gif|png|ico)$">
ExpiresActive on
ExpiresDefault "access plus 1 year"
</filesmatch>
<filesmatch "\.(css|js)$">
ExpiresActive on
ExpiresDefault "access plus 7 day"
</filesmatch>
</ifmodule>
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
</filesmatch>
### 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]
</directory>
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]
</virtualhost>
Previous →
Job Control Commands: fg, bg and ctrl-z