htaccess cheatsheet

Problems with the Linux version of XAMPP, questions, comments, and anything related.

htaccess cheatsheet

Postby apachedude » 14. March 2007 20:32

Heres my list of the ultimate htaccess code snippets and examples that I use all the time. I tried to keep them extremely minimalistic.

Each code snippet has been copied from htaccesselite. Additional and detailed info on each htaccess code snippet can be found at htaccessElite

Most of these snippets can be used with a Files or Filesmatch directive to only apply to certain files.

Make any file be a certain filetype (regardless of name or extension)
Code: Select all
#Makes image.gif, blah.html, index.cgi all act as php
ForceType application/x-httpd-php

Authentication Magic

Require password for 1 file:
Code: Select all
<Files login.php>
AuthName "Prompt"
AuthType Basic
AuthUserFile /home/
Require valid-user

Protect multiple files:
Code: Select all
<FilesMatch "^(exec|env|doit|phpinfo|w)*$">
AuthName "Development"
AuthUserFile /.htpasswd
AuthType basic
Require valid-user

Example uses of the Allow Directive:
Code: Select all
# A (partial) domain-name
Allow from

# Full IP address
Allow from

# More than 1 full IP address
Allow from

# Partial IP addresses
# first 1 to 3 bytes of IP, for subnet restriction.
Allow from 10.1
Allow from 10 172.20 192.168.2

# network/netmask pair
Allow from

# network/nnn CIDR specification
Allow from

# IPv6 addresses and subnets
Allow from 2001:db8::a00:20ff:fea7:ccea
Allow from 2001:db8::a00:20ff:fea7:ccea/10

Using visitor dependent environment variables:
Code: Select all
SetEnvIf User-Agent ^KnockKnock/2\.0 let_me_in
Order Deny,Allow
Deny from all
Allow from env=let_me_in

Allow from but deny from
Code: Select all
Order Allow,Deny
Allow from
Deny from

Allow from IP address with no password prompt, and also allow from non-Ip address with password prompt:
Code: Select all
AuthUserFile /home/www/site1-passwd
AuthType Basic
AuthName MySite
Require valid-user
Allow from 172.17.10
Satisfy Any

block access to files during certain hours of the day
Code: Select all
# If the hour is 16 (4 PM) Then deny all access
RewriteCond %{TIME_HOUR} ^16$   
RewriteRule ^.*$ - [F,L]

Redirect non-https requests to https server fixing double-login problem and ensuring that htpasswd authorization can only be entered using HTTPS
Code: Select all
SSLOptions +StrictRequire
SSLRequire %{HTTP_HOST} eq ""
ErrorDocument 403

SEO Friendly redirects for bad/old links and moved links
For single moved file
Code: Select all
Redirect 301 /d/file.html

For multiple files like a blog/this.php?gh
Code: Select all
RedirectMatch 301 /blog(.*)$1

different domain name
Code: Select all
Redirect 301 /

Require the www
Code: Select all
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$$1 [R=301,L]

Redirect everyone to different site except 1 IP address (useful for web-development)
Code: Select all
ErrorDocument 403
Order deny,allow
Deny from all
Allow from

CHMOD your files
chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600
chmod files that you really don't want people to see as 400
NEVER chmod 777, if something requires write access use 766

Variable (mod_env) Magic
Set the Timezone of the server:
Code: Select all
SetEnv TZ America/Indianapolis

Set the Server Administrator Email:

Turn off the ServerSignature
Code: Select all
ServerSignature Off

Add a "en" language tag and "text/html; UTF-8" headers without meta tags
Code: Select all
AddDefaultCharset UTF-8
# Or AddType 'text/html; charset=UTF-8' html
DefaultLanguage en-US

Use a custom php.ini

Detailed instructions for doing this whether you are using php as a cgi or the apache module mod_php

Securing directories: Remove the ability to execute scripts

Heres a couple different ways I do it
Code: Select all
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI

This is cool, you are basically categorizing all those files that end in those extensions so that they fall under the jurisdiction of the -ExecCGI command, which also means -FollowSymLinks (and the opposite is also true, +ExecCGI also turns on +FollowSymLinks)

Only allow GET and PUT request methods to your server.

Code: Select all
Options -ExecCGI -Indexes -All
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD) RewriteRule .* - [F]

Processing All gif files to be processed through a cgi script
Code: Select all
Action image/gif /cgi-bin/filter.cgi

Process request/file depending on the request method
Code: Select all
Script PUT /cgi-bin/upload.cgi

Force Files to download, not be displayed in browser

Code: Select all
AddType application/octet-stream .avi
AddType application/octet-stream .mpg

Then in your HTML you could just link directly to the file..
Code: Select all
<a href="/movies/mov1.avi">Download Movie1</a>

And then you will get a pop-up box asking whether you want to save the file or open it.

Show the source of dynamic files

If you'd rather have .pl, .py, or .cgi files displayed in the browser as source rather than be executed as scripts, simply create a .htaccess file in the relevant directory with the following:

Code: Select all
RemoveHandler cgi-script .pl .py .cgi

Dramatically Speed up your site by implementing Caching!

Code: Select all
<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|swf)$">
Header set Cache-Control "max-age=2592000"

<FilesMatch "\.(js|css|pdf|txt)$">
Header set Cache-Control "max-age=604800"

<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=43200"

Prevent Files image/file hotlinking and bandwidth stealing

Code: Select all
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ [R=302,L]


Code: Select all
ErrorDocument 404 /favicon.ico
ErrorDocument 403

Code: Select all
ErrorDocument 404 /cgi-bin/error.php
ErrorDocument 400 /cgi-bin/error.php
ErrorDocument 401 /cgi-bin/error.php
ErrorDocument 403 /cgi-bin/error.php
ErrorDocument 405 /cgi-bin/error.php
ErrorDocument 406 /cgi-bin/error.php
ErrorDocument 409 /cgi-bin/error.php
ErrorDocument 413 /cgi-bin/error.php
ErrorDocument 414 /cgi-bin/error.php
ErrorDocument 500 /cgi-bin/error.php
ErrorDocument 501 /cgi-bin/error.php

Note: You can also do an external link, but don't do an external link to your site or you will cause a loop that will hurt your SEO.

Heres the full list..

Page 1: For Webmasters
When site is ‘Under Construction’
Redirect everyone to different site except 1 IP
Redirect everyone to different site except 1 IP
Redirect Everyone but you to alternate page on your server.
Set the Timezone of the server
Set the Server Administrator Email
Turn off the ServerSignature
Force Files to download, do not display in browser
Process All .gif files with a cgi script
Process Requests with certain Request Methods
Make any file be a certain filetype
Use IfModule directive for robust code

Page 2: Custom HTTP Headers
Prevent Caching 100%
Remove IE imagetoolbar without meta tag
Add Privacy (P3P) Header to your site
Add a ‘en-US’ language header and ‘UTF-8′ without meta tags!
Using AddType
Using the Files Directive
Using the FilesMatch Directive

Page 3: PHP htaccess tips
When php run as CGI
Use a custom php.ini with mod_php or php as a cgi
When php run as Apache Module (mod_php)
When cgi php is run with wrapper (FastCGI)

Page 4: SEO Search Engine Friendly Redirects without mod_rewrite
For single moved file
Redirect Home to new Domain
For multiple files like a blog/this.php?gh
Redirect Entire site to single file

Page 5: mod_rewrite tips and tricks
Mostly .htaccess rewrite examples should begin with:
Check for a key in QUERY_STRING
Removes the QUERY_STRING from the URL
Fix for infinite loops
Require the www
Require no www
Redirect .php files to .html files (SEO friendly)
Redirect .html files to actual .php files (SEO friendly)
block access to files during certain hours of the day
Rewrite underscores to hyphens for SEO URL
Require the www without hardcoding
Require no subdomain
Require no subdomain
Redirecting Wordpress Feeds to Feedburner
Only allow GET and PUT request methods
Prevent Files image/file hotlinking and bandwidth stealing
Stop browser prefetching
Make a prefetching hint for Firefox.

Page 6: Speed up your site with Caching and cache-control
htaccess time cheatsheet
Caching with both mod_expires + mod_headers
Caching with mod_headers
Caching with mod_expires

Page 7: Apache Authentication in htaccess
Require password for 1 file only
Protect multiple files:
Using the Apache Allow Directive in htaccess
network/netmask pair
IP address
More than 1 IP address
Partial IP addresses, first 1 to 3 bytes of IP, for subnet restriction
network/nnn CIDR specification
IPv6 addresses and subnets
Deny subdomains
Allow from IP without password prompt, and also allow from any address with password prompt
Skeleton .htaccess file to start with

Page 8: Security with Apache htaccess
CHMOD your files
Prevent access to .htaccess and .htpasswd files
Show Source Code instead of executing
Securing directories: Remove the ability to execute scripts
Common STATUS Codes and ErrorDocument Implementations
When using CGI PHP, php 404 Error example
An example 404 Error page in perl cgi
ErrorDocuments generated by Apache

Page 9: SSL example usage in htaccess
Redirect non-https requests to https server
Rewrite non-https to HTTPS without mod_ssl!
Based on HTTPS variable (best)
Redirect everything served on port 80 to HTTPS URI
Redirect particular URLs to a secure version in an SSL SEO method
Check to see whether the HTTPS environment variable is set
Rewrite to SSL or NON-SSL using relative URL!

Page 10: Apache Variable fun (mod_env)
Using visitor dependent environment variables:
Special Purpose Environment Variables
SetEnvIfNoCase Example
SetEnvIfNoCase Example 2
Posts: 2
Joined: 09. January 2007 11:52

Postby JKMickelson » 15. March 2007 06:31


A most excellent article. I found solutions to a number of questions I had. In abundance, thank you!

Posts: 30
Joined: 23. February 2007 09:56

Return to XAMPP for Linux

Who is online

Users browsing this forum: No registered users and 6 guests