<?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; Web Hosting</title>
	<atom:link href="http://www.askapache.com/web-hosting/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.askapache.com</link>
	<description>Advanced Web Development</description>
	<lastBuildDate>Thu, 19 Nov 2009 12:21:49 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Optimizing Servers and Processes for Speed with ionice, nice, ulimit</title>
		<link>http://www.askapache.com/linux-unix/optimize-nice-ionice.html</link>
		<comments>http://www.askapache.com/linux-unix/optimize-nice-ionice.html#comments</comments>
		<pubDate>Sat, 10 Oct 2009 05:41:28 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[Review]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Server Administration]]></category>
		<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[Webmaster]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[chrt]]></category>
		<category><![CDATA[CPU Scheduling]]></category>
		<category><![CDATA[Disk IO]]></category>
		<category><![CDATA[ionice]]></category>
		<category><![CDATA[iostat]]></category>
		<category><![CDATA[Nice]]></category>
		<category><![CDATA[optimize processes]]></category>
		<category><![CDATA[Renice]]></category>
		<category><![CDATA[servers]]></category>
		<category><![CDATA[taskset]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=3167</guid>
		<description><![CDATA[<p><a href="http://www.askapache.com/linux-unix/optimize-nice-ionice.html" class="IFL"><img src="/wp-content/uploads/2009/10/nice-chart-115x74.png" alt="NICE Levels Chart" title="NICE Levels Chart" width="115" height="74" /></a>To prepare for several upcoming articles on AskApache that are focused on optimizing Servers and Sites from a server admin level, here is an article to introduce the main tools that we will be using.  These tools are used to optimize CPU time for each process using <strong>nice</strong> and <strong>renice</strong>, and other tools like <strong>ionice</strong> are used to optimize the Disk IO, or Disk speed / Disk traffic for each process.  Then you can make sure your mysqld and httpd processes are always fast and prioritized.<br class="C" /></p> ]]></description>
			<content:encoded><![CDATA[<p>Ok, sup.  I really felt I had to get this out of the way, because I have a whole stack of drafts waiting to be published, but I realized that not many people will benefit from all the advanced optimizations and tricks I&#8217;m writing unless they get a basic understanding of some of the tools I&#8217;m using.  I decided to write a series of articles explaining how I optimize servers for speed because lately I&#8217;ve been getting a lot more people wanting to hire me to do that.  I take on projects when I can but there is clearly a need out here on the net for some self-help.   The momentum is swinging more and more towards VPS type of web hosting, and I would say that 99% of those customers are getting supremely ripped off, which goes against the foundation of the web.</p>
<p>Keep in mind that this blog and my research is only a hobby of mine, my job is primarily marketing and sales, so I&#8217;m not some licensed expert or anything, or even an unlicensed expert! haha.  But it does bother me that those who are tech-savvy enough to run web-hosting companies are happily ripping people off.  So this article details the main tools that are used to speed up and optimize your machine by delegating levels of priority to specific processes.  Future articles will use these tools alot, so this is meant as an intro.</p>
<p><a id="cpu-disk-io" name="cpu-disk-io"></a></p>
<h2>CPU and Disk I/O</h2>
<p>As most of you are aware, there are 2 variables that determine any computer or programs speed.  CPU and Disk I/O.  CPU determines how fast you can process data, crunch numbers, etc. while disk I/O determines how fast your disks can read and write data to the hard-drive.  Wouldn&#8217;t it be great if you could easily configure your server to give your httpd, php, and other processes both greater CPU processing and disk IO than your non-important processes like backup scripts, ftp daemons, etc.?  We are talking about Linux in this article, so of course YES not only can you do that, you should!</p>
<p><a name="optimize-ram" id="optimize-ram"></a></p>
<h3>RAM</h3>
<p>RAM is like a hard-drive in that data is stored on it, and read/written to it.  The difference is that RAM is somewhere around 30x faster than disk I/O, but the cost of that incredible speed is that the data stored on it is only temporary in the sense that it won&#8217;t be stored permanently, it is completely erased when your machine is rebooted.  RAM is also expensive, and there is a limit to how much a server or machine can have due to hardware limits.</p>
<p><a name="optimize-swap" id="optimize-swap"></a></p>
<h3>SWAP</h3>
<p>SWAP takes off when you run out of RAM but you still want certain data to be read/write quickly.  Basically when you start running out of RAM your machine starts supplementing RAM with SWAP storage.  SWAP is usually a partition on a second hard-drive disk.  There is an upper limit on how much I/O can occur on a disk at one time, and the more I/O takes place, the slower all I/O becomes, so SWAP works well on a separate hard-drive as it will have much faster I/O.  On Windows they opted to copy the SWAP mechanism but instead use a file named pagefile.sys, and that is just one reason people in the know do not care for Windows.</p>
<p><a name="optimize-cpu" id="optimize-cpu"></a></p>
<h3>CPU</h3>
<p>So lets do this, think of your CPU (your processor) as having an amount of 100% processing available when not being used, 0% when its maxed out.  CPU&#8217;s handle multiple processing tasks simultaneously, so what we will discuss in this article is how to specify HOW MUCH of that processing amount each of your programs (heretofore &#8220;processes&#8221;) are able to use.  Yes, very very cool.</p>
<p>That is correct, you can easily configure your server to provide more of the available processing time to certain programs over others, like you can configure apache and php to utilize 50% of your CPU processing time by themselves, so that all other processes (proftpd, sshd, rsync, etc.) combined can only utilize 50%.  The terminology is we can give certain specific processes (like php.cgi, httpd, fast-cgi.cgi) a specific <strong>priority</strong>, where -19 is the most priority, and +19 is the least amount of priority, or CPU processing time.  I know it seems backwards.. </p>
<p><a id="tools" name="tools"></a></p>
<h2>The Tools</h2>
<p>If you run Windows, you are in the right place&#8230; because the following advice will save your life:  GET LINUX! Ok, now that that is out of the way, the following are the tools dicussed on this page.  All of them are free, open-source, and wonderful.  The basic idea of these tools is to control how much CPU is devoted to each process, and also how much Disk IO/Disk traffic is given to each process.</p>
<dl>
<dt><a href="#nice-tool">nice</a></dt>
<dd>run a program with modified scheduling priority</dd>
<dt><a href="#renice-tool">renice</a></dt>
<dd>alter priority of running processes</dd>
<dt><a href="#ionice-tool">ionice</a></dt>
<dd>set or retrieve the I/O priority for a given pid or execute a new task with a given I/O priority.</dd>
<dt><a href="#iostat-tool">iostat</a></dt>
<dd>Report Central Processing Unit (CPU) statistics and input/output statistics for devices and partitions.</dd>
<dt><a href="#ulimit-tool">ulimit</a></dt>
<dd>Ulimit provides control over the resources available to processes started by the shell, on systems that allow such control.</dd>
<dt><a href="#chrt-tool">chrt</a></dt>
<dd>set or retrieve real-time scheduling parameters for a given pid or execute a new task under given scheduling parameters.</dd>
<dt><a href="#taskset-tool">taskset</a></dt>
<dd>set or retrieve task CPU affinity for a given pid or execute a new task under a given affinity mask.</dd>
<dt></dt>
<dd></dd>
</dl>
<p><a id="part1-processes" name="part1-processes"></a></p>
<h2>Part 1: Process Processes Faster</h2>
<p>Ok so lets tackle figuring out how to give your response-intensive processes (like apache, php, ruby, perl, java) meaning a request to your server/machine requires a <em>response</em>.  For instance, when you requested this page that you are reading at this very second, several things on my server had to happen for you to be able to read this.</p>
<p>First your computer sends out a request to see what server the www.askapache.com domain name is.  DNS servers respond with my server IP, so for servers dedicated as nameservers, optimizing the DNS processes like bind would speed that up.  Now that your computer knows how to reach my server it sends an HTTP GET request for this url.  This request is received by the httpd process that is apache, and apache determines this url should be handled by my custom compiled php5.3.0 binary, because this page is WordPress generated.  So the php binary loads up the WordPress /index.php file, which chain-loads several other php files, including <code>wp-config.php</code> containing my MySql database settings.  Now php connects to my MySql Server to fetch this articles content, comments, title, tags, etc. and then generates the HTML and hands that back to Apache.</p>
<p>Finally, Apache generates a HTTP RESPONSE and sends the RESPONSE and CONTENT back to your Browser, which then in turn renders the page for your eyes with the necessary javascript, images, css, and other files included in the HTML response.</p>
<h3>Too much Processing</h3>
<p>Now you see why I&#8217;ve opted to write my own caching plugin that takes the php and mysql processes OUT of that equation.  Both the php binary and the mysql instance consume CPU processing, and disk IO, to load all their library files, make various network requests and sockets, check permissions, and on and on.  And that&#8217;s completely ok, the thing is, unless you configure these processes (Apache, PHP, MySQL) they will use the same amount of CPU processing that other processes use, other processes that have very little to do with you reading this sentence.  Processes to run my mail server, my FTP server, my SSH server, my cronjobs, cleanup scripts, atd daemon, etc.. and they will get the same amount of CPU!</p>
<p>Another even simpler example is what got me to look into this myself.  I wrote a shell script that created hourly, daily, weekly, and monthly backups for all of my websites and sql databases, and set it up to run by cronjob at those set intervals.  Eventually I noticed my sites were slower, my php even slower, and sometimes I even saw 503 errors that my host throws up when my server is overloaded.  The research that I pursued to prevent that from happening has been hugely eye-opening.  What does a backup script do?  Mine just created tar archives of all the files in my web root, then gzipped the tar archive saving to a backup server using scp (a file transfer using ssh).  This resulted in the following huge problems that seem to have nothing to do with a faster server and speedier website, but they have everything to with it.</p>
<ol>
<li><strong>CPU Bottleneck #1</strong> &#8211; tar and gzip use compression algorithms at a low level to create a compressed version, and all that compressing uses a whole lot of crunching &#8211; CPU processing</li>
<li><strong>DISK IO Bottleneck</strong> &#8211; Tarring the whole web root directory was creating a ton of disk io, and remember the more disk io that is going on, the less is available for everything else.</li>
<li><strong>CPU Bottleneck #2</strong> &#8211; Using scp to send my backups was security-smart, but these huge archive files had to be encrypted and sent over the net.</li>
</ol>
<p><a id="breaking-bottlenecks" name="breaking-bottlenecks"></a></p>
<h2>Breaking Bottles</h2>
<p>I apologize for being a little long-winded there, but I think it&#8217;s important to make sure everyone understands those basic concepts, which are foreign to most people.  Once you understand what is causing the bottlenecks, then you can understand the solutions, which actually are incredibly simple and even a novice linux user can easily do.  Besides, the net gets a little bit faster every time someone implements this.</p>
<p><a id="nice-tool" name="nice-tool"></a></p>
<h3>nice</h3>
<p><img src="/wp-content/uploads/2009/10/nice-chart.png" alt="NICE Levels Chart" title="NICE Levels Chart" width="351" height="225" class="IFL" />Nice allows you to run a program with modified scheduling priority which specifies how much CPU is devoted to a particular process.  Run COMMAND with an adjusted niceness, which affects process scheduling.  With no COMMAND, print the current niceness.  </p>
<p>Nicenesses range from -20 (most favorable scheduling) to 19 (least favorable).   <code>-n, &#45;-adjustment=N</code> &#8211;  add integer N to the niceness (default 10).   <code>nice +19</code> tasks get a HZ-independent 1.5%.  Running a <code>nice +10</code> and a <code>nice +11</code> task means the first will get 55% of the CPU, the other 45%.<br class="C" /></p>
<p><a id="nice-usage" name="nice-usage"></a></p>
<h4>nice usage</h4>
<pre>nice [OPTION] [COMMAND [ARG]&#46;..]
&nbsp;
-n, &#45;-adjustment=ADJUST   increment priority by ADJUST first</pre>
<p><a id="nice-examples" name="nice-examples"></a></p>
<h4>Examples of nice</h4>
<p>Using nice to download a file</p>
<pre>nice -n 17 curl -q -v -A &#039;Mozilla/5.0&#039; -L -O http://wordpress.org/latest.zip</pre>
<p>Unzipping a file with nice</p>
<pre>nice -n 17 unzip latest.zip</pre>
<p>Nice way to build from source</p>
<pre>nice -n 2 ./configure
nice -n 2 make
nice -n 2 make install</pre>
<p>It is sometimes useful to run non-interactive programs with reduced priority.</p>
<pre>$ nice factor `echo &#039;2^9 - 1&#039;|bc`
511: 7 73</pre>
<p>Since nice prints the current priority, we can invoke it through itself to demonstrate how it works: The default behavior is to reduce priority by 10.</p>
<pre> $ nice nice
10
$ nice -n 10 nice
10</pre>
<p> The ADJUSTMENT is relative to the current priority.  The first <code>nice</code> invocation runs the second one at priority 10, and it in turn runs the final one at a priority lowered by 3 more.</p>
<pre>$ nice nice -n 3 nice
13</pre>
<p>Specifying a priority larger than 19 is the same as specifying 19.</p>
<pre>$ nice -n 30 nice
19</pre>
<p>Only a privileged user may run a process with higher priority.</p>
<pre>$ nice -n -1 nice
nice: cannot set priority: Permission denied
$ sudo nice -n -1 nice
-1</pre>
<blockquote cite="/wp-content/uploads/2009/08/sched-nice-design.txt">
<p>The new scheduler in v2.6.23 addresses all three types of complaints:</p>
<p>To address the first complaint (of nice levels being not &#8220;punchy&#8221; enough), the scheduler was decoupled from &#8216;time slice&#8217; and HZ concepts (and granularity was made a separate concept from nice levels) and thus it was possible to implement better and more consistent nice +19 support: with the new scheduler nice +19 tasks get a HZ-independent 1.5%, instead of the variable 3%-5%-9% range they got in the old scheduler.</p>
<p>To address the second complaint (of nice levels not being consistent), the new scheduler makes nice(1) have the same CPU utilization effect on tasks, regardless of their absolute nice levels. So on the new scheduler, running a nice +10 and a nice 11 task has the same CPU utilization &#8220;split&#8221; between them as running a nice -5 and a nice -4 task. (one will get 55% of the CPU, the other 45%.) That is why nice levels were changed to be &#8220;multiplicative&#8221; (or exponential) &#8211; that way it does not matter which nice level you start out from, the &#8216;relative result&#8217; will always be the same.</p>
<p>The third complaint (of negative nice levels not being &#8220;punchy&#8221; enough and forcing audio apps to run under the more dangerous SCHED_FIFO scheduling policy) is addressed by the new scheduler almost automatically: stronger negative nice levels are an automatic side-effect of the recalibrated dynamic range of nice levels.</p>
</blockquote>
<p><a id="renice-tool" name="renice-tool"></a></p>
<h3>renice</h3>
<p>Renice is similar to the nice command, but it lets you modify the nice of a currently running process.  This is nice for shell scripts where you can add this to the top of the script to nicify the whole script to 19.</p>
<p><a id="renice-usage" name="renice-usage"></a></p>
<h4>renice usage</h4>
<pre>renice priority [ [ -p ] pids ] [ [ -g ] pgrps ] [ [ -u ] users ]
&nbsp;
-g      Force who parameters to be interpreted as process group ID&#039;s.
-u      Force the who parameters to be interpreted as user names.
-p      Resets the who interpretation to be (the default) process ID&#039;s.</pre>
<p><a id="renice-examples" name="renice-examples"></a></p>
<h4>Examples of renice</h4>
<p>From the shell, changes the priority of the shell and all children to 19.  From a shell script, does the same but only for the script and its children.</p>
<pre>renice 19 -p $$</pre>
<p>This runs renice without any output</p>
<pre>renice 19 -p $$ &&gt;/dev/null</pre>
<p>10 gets more CPU than 19</p>
<pre>renice 10 -p $$</pre>
<p>change the priority of process ID&#8217;s 987 and 32, and all processes owned by users daemon and root.</p>
<pre>renice +1 987 -u daemon root -p 32</pre>
<p><a id="part2-disk-io" name="part2-disk-io"></a></p>
<h2>Part 2: Optimizing Disk I/O</h2>
<p><a id="scheduling-policies" name="scheduling-policies"></a></p>
<h3>Linux Scheduling Policies</h3>
<p>The scheduler is the kernel component that decides which runnable process will be executed by the CPU next.  Each process has an associated scheduling policy and a static scheduling priority, sched_priority</p>
<p>Processes scheduled under one of the real-time policies (SCHED_FIFO, SCHED_RR) have a sched_priority value in the <strong>range 1 (low) to 99 (high)</strong>.  (As the numbers imply, real-time processes always have higher priority than normal processes.)   The following &#8220;real-time&#8221; policies are also supported, for special time-critical applications that need precise control over the way in which runnable processes are selected for execution:</p>
<p>Currently, Linux supports the following &#8220;normal&#8221; (i.e., non-real-time) scheduling policies:</p>
<dl>
<dt><strong>SCHED_OTHER</strong>: Default Linux time-sharing scheduling</dt>
<dd>The standard round-robin time-sharing policy</dd>
<dt><strong>SCHED_BATCH</strong>: Scheduling batch processes</dt>
<dd>This policy is useful for workloads that are non-interactive, but do not want to lower their nice value, and for workloads that want a deterministic scheduling policy without interactivity causing extra preemptions (between the workload&#8217;s tasks).</dd>
<dt><strong>SCHED_IDLE</strong>: Scheduling very low priority jobs</dt>
<dd>This policy is intended for running jobs at extremely low priority (lower even than a +19 nice value with the SCHED_OTHER or SCHED_BATCH policies)</dd>
<dt><strong>SCHED_FIFO</strong>: First In-First Out scheduling</dt>
<dd>A first-in, first-out policy</dd>
<dt><strong>SCHED_RR</strong>: Round Robin scheduling</dt>
<dd>A round-robin policy.</dd>
</dl>
<p><a id="scheduling-classes" name="scheduling-classes"></a></p>
<h3>Scheduling Classes</h3>
<dl>
<dt><code>IOPRIO_CLASS_RT</code></dt>
<dd>This is the realtime io class. The RT scheduling class is given first access to the disk, regardless of what else is going on in the system. Thus the RT class needs to be used with some care, as it can starve other processes. As with the best effort class, 8 priority levels are defined denoting how big a time slice a given process will receive on each scheduling window.  This scheduling class is given higher priority than any other in the system, processes from this class are given first access to the disk every time. Thus it needs to be used with some care, one io RT process can starve the entire system. Within the RT class, there are 8 levels of class data that determine exactly how much time this process needs the disk for on each service. In the future this might change to be more directly mappable to performance, by passing in a wanted data rate instead.</dd>
<dt><code>IOPRIO_CLASS_BE</code></dt>
<dd>This is the best-effort scheduling class, which is the default for any process that hasn&#8217;t set a specific io priority. This is the default scheduling class for any process that hasn&#8217;t asked for a specific io priority. Programs inherit the CPU nice setting for io priorities. This class takes a priority argument from 0-7, with lower number being higher priority. Programs running at the same best effort priority are served in a round-robin fashion.  The class data determines how much io bandwidth the process will get, it&#8217;s directly mappable to the cpu nice levels just more coarsely implemented. 0 is the highest BE prio level, 7 is the lowest. The mapping between cpu nice level and io nice level is determined as: io_nice = (cpu_nice + 20) / 5.</dd>
<dt><code>IOPRIO_CLASS_IDLE</code></dt>
<dd>This is the idle scheduling class, processes running at this level only get io time when no one else needs the disk. A program running with idle io priority will only get disk time when no other program has asked for disk io for a defined grace period. The impact of idle io processes on normal system activity should be zero. This scheduling class does not take a priority argument.    The idle class has no class data, since it doesn&#8217;t really apply here.</dd>
</dl>
<p><a id="ionice-tool" name="ionice-tool"></a></p>
<h3>ionice</h3>
<p>ionice &#8211; get/set program io scheduling class and priority.  This program sets the io scheduling class and priority for a program.  Since v3 (aka CFQ Time Sliced) CFQ implements I/O nice levels similar to those of CPU scheduling. These nice levels are grouped in three scheduling classes each one containing one or more priority levels:</p>
<p><a id="ionice-usage" name="ionice-usage"></a></p>
<h4>ionice usage</h4>
<p>If no arguments or just -p is given, ionice will query the current io scheduling class and priority for that process.</p>
<pre>ionice [-c] [-n] [-p] [COMMAND [ARG&#46;..]]</pre>
<ul>
<li><strong>-c</strong> &#8211; The scheduling class. 1 for real time, 2 for best-effort, 3 for idle.</li>
<li><strong>-n</strong> &#8211; The scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data.</li>
<li><strong>-p</strong> &#8211; Pass in a process pid to change an already running process. If this argument is not given, ionice will run the listed program with the given parameters.</li>
</ul>
<p><a id="ionice-examples" name="ionice-examples"></a></p>
<h4>ionice Examples</h4>
<p>Sets process with PID 89 as an idle io process.</p>
<pre>ionice -c3 -p89</pre>
<p>Runs &#8216;bash&#8217; as a best-effort program with highest priority.</p>
<pre>ionice -c2 -n0 bash</pre>
<p>Returns the class and priority of the process with PID 89</p>
<pre>ionice -p89</pre>
<blockquote cite="http://gaarai.com/2009/03/06/multitasking-from-the-linux-command-line-plus-process-prioritization/">
<p>
<p>With the ionice command, you can set the IO priority for a process to one of three classes: Idle (3), Best Effort (2), and Real Time (1). The Idle class means that the process will only be able to read and write to the disk when all other processes are not using the disk. The Best Effort class is the default and has eight different priority levels from 0 (top priority) to 7 (lowest priority). The Real Time class results in the process having first access to the disk irregardless of other process and should never be used unless you know what you are doing.</p>
<p>If we wish to run the updatedb process in the background with an Idle IO class priority, we can run the following:</p>
<pre>
$ sudo date
$ sudo updatedb &#038;
[1] 16324
$ sudo ionice -c3 -p16324
</pre>
<p>If we’d rather just lower the Best Effort class priority (defaults to 4) for the command so the process isn’t limited to idle IO periods, we can run the following:</p>
<pre>
$ sudo date
$ sudo updatedb &#038;
[1] 16324
$ sudo ionice -c2 -n7 -p16324
</pre>
<p>Again, the Real Time class should not be used as it can prevent you from being able to interact with your system.</p>
<p>You may wonder where you can get the process ID if you don’t know it, can’t remember it, or didn’t start the process (an automatted script may have launched it). You can find process IDs with the ps command.</p>
<p>For example, if I had an updatedb program running in the background, and I wanted to find its process ID, I can run the following:</p>
<pre>
$ ps -C updatedb
PID TTY TIME CMD
4234 ? 00:00:42 updatedb
</pre>
<p>This tells me that the process’ process ID (PID) is 4234.</p>
</p>
</blockquote>
<p><a id="iostat-tool" name="iostat-tool"></a></p>
<h3>iostat</h3>
<p><a id="iostat-usage" name="iostat-usage"></a></p>
<h4>iostat Usage</h4>
<pre>iostat [ -c ] [ -d ] [ -N ] [ -n ] [ -h ] [ -k | -m ] [ -t ] [ -V ] [ -x ] [ -z ] [ &lt;device&gt; [&#46;..] | ALL ] [ -p [ &lt;device&gt; [,&#46;..] | ALL ] ] [ &lt;interval&gt; [ &lt;count&gt; ] ]

-c     The -c option is exclusive of the -d option and displays only the CPU usage report.
-d     The -d option is exclusive of the -c option and displays only the device utilization report.
-k     Display statistics in kilobytes per second instead of blocks per second.  Data displayed are valid only with kernels 2.4 and newer.
-m     Display statistics in megabytes per second instead of blocks or kilobytes per second.  Data displayed are valid only with kernels 2.4 and newer.
-n     Displays the NFS-directory statistic.  Data displayed are valid only with kernels 2.6.17 and newer.  This option is exclusive ot the -x option.
-h     Display the NFS report more human readable.
-p [ { device | ALL } ]   The  -p  option  is  exclusive  of  the -x option and displays statistics for block devices and all their partitions that are used by the system.
-t     Print the time for each report displayed.
-x     Display extended statistics.
</pre>
<p><a id="iostat-examples" name="iostat-examples"></a></p>
<h4>iostat Examples</h4>
<pre>iostat -p ALL 2 1000
avg-cpu:  %user   %nice    %sys %iowait   %idle
            8.34    0.08    1.26    2.27   88.05
</pre>
<p>Display a single history since boot report for all CPU and Devices.</p>
<pre>$ iostat</pre>
<p>Display a continuous device report at two second intervals.</p>
<pre>$ iostat -d 2</pre>
<p>Display six reports at two second intervals for all devices.</p>
<pre>$ iostat -d 2 6</pre>
<p>Display six reports of extended statistics at two second intervals for devices hda and hdb.</p>
<pre>$ iostat -x hda hdb 2 6</pre>
<p>Display six reports at two second intervals for device sda and all its partitions (sda1, etc.)</p>
<pre>$ iostat -p sda 2 6</pre>
<p><a id="schedule-utils" name="schedule-utils"></a></p>
<h2>Schedule Utils</h2>
<p>These are the Linux scheduler utilities &#8211; schedutils for short.  These programs take advantage of the scheduler family of syscalls that Linux implements across various kernels.  These system calls implement interfaces for scheduler-related parameters such as CPU affinity and real-time attributes.  The standard UNIX utilities do not provide support for these interfaces &#8212; thus this package.</p>
<p>The programs that are included in this package are chrt and taskset.  Together with nice and renice (not included), they allow full control of process scheduling parameters.  Suggestions for related utilities are welcome, although it is believed (barring new interfaces) that all scheduling interfaces are covered.</p>
<p>I&#8217;ve found that quite a few servers do not have this package installed, indicating to you that they might not know what they are doing.  Here is how you can install this incredible package, for non-root users.  Root users know how to do this, or they shouldn&#8217;t be root.  Download and install in 1 line provided you have curl.  Or just use the following commands.</p>
<pre>mkdir -pv $HOME/{dist,source,bin,share/man/man1} &#038;&#038; cd ~/dist &#038;&#038; curl -O http://ftp.de.debian.org/debian/pool/main/s/schedutils/schedutils_1.5.0.orig.tar.gz &#038;&#038; cd ~/source &#038;&#038; tar -xvzf ~/dist/sch*z &#038;&#038; cd sch* &#038;&#038; sed -i -e &#039;s,= /usr/local,=${HOME},g&#039; Makefile &#038;&#038; make &#038;&#038; make install &#038;&#038; make installdoc</pre>
<pre>
mkdir -pv $HOME/{dist,source,bin,share/man/man1}
cd ~/dist &#038;&#038; curl -O http://ftp.de.debian.org/debian/pool/main/s/schedutils/schedutils_1.5.0.orig.tar.gz
cd ~/source &#038;&#038; tar -xvzf ~/dist/schedutils_1.5.0.orig.tar.gz
cd ~/source/schedutils-1.5.0 &#038;&#038; sed -i -e &#039;s,= /usr/local,=${HOME},g&#039; Makefile
make || make -d &#038;&#038; make install || make install -d &#038;&#038; make installdoc || make installdoc -d
</pre>
<p><a id="taskset-tool" name="taskset-tool"></a></p>
<h3>taskset</h3>
<p>Taskset  is  used to set or retrieve the CPU affinity of a running process given its PID or to launch a new COMMAND with a given CPU affinity.  CPU affinity is a scheduler property that &#8220;bonds&#8221; a process to a given set of CPUs on the system.  The Linux scheduler will honor the given CPU affinity and the process will not run on any other CPUs.  Note that the Linux scheduler also supports natural CPU affinity: the scheduler attempts to keep processes on the same CPU as long as practical for performance reasons.  Therefore, forcing a specific CPU affinity is useful only in certain applications.</p>
<p>The  CPU  affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU.  Not all CPUs may exist on a given system but a mask may specify more CPUs than are present.  A retrieved mask will reflect only the bits that correspond to CPUs physically on the system.  If an invalid mask is given (i.e., one that corresponds to no valid CPUs on the current system) an error is returned.  A user must possess CAP_SYS_NICE to change the CPU affinity of a process.  Any user can retrieve the affinity mask.</p>
<p><a id="taskset-usage" name="taskset-usage"></a></p>
<h4>taskset Usage</h4>
<pre>taskset [options] [mask | cpu-list] [pid | cmd [args&#46;..]]
&nbsp;
-p, &#45;-pid            operate on existing given pid
-c, &#45;-cpu-list     display and specify cpus in list format</pre>
<p><a id="taskset-examples" name="taskset-examples"></a></p>
<h4>taskset-examples</h4>
<p>The default behavior is to run a new command:</p>
<pre>$ taskset 03 sshd -b 1024</pre>
<p>You can retrieve the mask of an existing task or set it:</p>
<pre>$ taskset -p 700
$ taskset -p 03 700</pre>
<p>List format uses a comma-separated list instead of a mask:</p>
<pre>$ taskset -pc 0,3,7-11 700</pre>
<p><a id="chrt-tool" name="chrt-tool"></a></p>
<h3>chrt</h3>
<p><code>chrt</code> sets or retrieves the real-time scheduling attributes of an existing PID or runs COMMAND with the given attributes.  Both policy (one of <code>SCHED_FIFO</code>, <code>SCHED_RR</code>, or <code>SCHED_OTHER</code>) and priority can be set and retrieved.  A user must possess CAP_SYS_NICE to change the scheduling attributes of a process.  Any user can retrieve the scheduling information.</p>
<p><a id="chrt-usage" name="chrt-usage"></a></p>
<h4>chrt Usage</h4>
<pre>chrt [options] [prio] [pid | cmd [args&#46;..]]
&nbsp;
-p, &#45;-pid operate on an existing PID and do not launch a new task
-f, &#45;-fifo set scheduling policy to SCHED_FIFO
-m, &#45;-max show minimum and maximum valid priorities, then exit
-o, &#45;-other set policy scheduling policy to SCHED_OTHER
-r, &#45;-rr set scheduling policy to SCHED_RR (the default)
</pre>
<p><a id="chrt-examples" name="chrt-examples"></a></p>
<h4>chrt Examples</h4>
<p>The default behavior is to run a new command:   <code>chrt [prio] &#45;- [command] [arguments]</code></p>
<p>You can also retrieve the real-time attributes of an existing task:</p>
<pre>chrt -p [pid]</pre>
<p>Or set them:</p>
<pre>chrt -p [prio] [pid]</pre>
<p><a id="ulimit-tool" name="ulimit-tool"></a></p>
<h2>ulimit &#8211; get and set user limits</h2>
<p>Ulimit provides control over the resources available to processes started by the shell, on systems that allow such control. One can set the resource limits of the shell using the built-in ulimit command.  The shell&#8217;s resource limits are inherited by the processes that it creates to execute commands.</p>
<p><a id="ulimit-usage" name="ulimit-usage"></a></p>
<h4>ulimit Usage</h4>
<pre>ulimit [-SHacdfilmnpqstuvx] [limit]</pre>
<dl>
<dt>-S</dt>
<dd>use the `soft&#8217; resource limit</dd>
<dt>-H</dt>
<dd>use the `hard&#8217; resource limit</dd>
<dt>-a</dt>
<dd>all current limits are reported</dd>
<dt>-c</dt>
<dd>the maximum size of core files created</dd>
<dt>-d</dt>
<dd>the maximum size of a process&#8217;s data segment</dd>
<dt>-f</dt>
<dd>the maximum size of files created by the shell</dd>
<dt>-l</dt>
<dd>the maximum size a process may lock into memory</dd>
<dt>-m</dt>
<dd>the maximum resident set size</dd>
<dt>-n</dt>
<dd>the maximum number of open file descriptors</dd>
<dt>-p</dt>
<dd>the pipe buffer size</dd>
<dt>-s</dt>
<dd>the maximum stack size</dd>
<dt>-t</dt>
<dd>the maximum amount of cpu time in seconds</dd>
<dt>-u</dt>
<dd>the maximum number of user processes</dd>
<dt>-v</dt>
<dd>the size of virtual memory</dd>
</dl>
<p>If LIMIT is given, it is the new value of the specified resource; the special LIMIT values `soft&#8217;, `hard&#8217;, and `unlimited&#8217; stand for the current soft limit, the current hard limit, and no limit, respectively.  Otherwise, the current value of the specified resource is printed.  If no option is given, then -f is assumed.  Values are in 1024-byte increments, except for -t, which is in seconds, -p, which is in increments of 512 bytes, and -u, which is an unscaled number of processes.</p>
<dl>
<dt>RLIMIT_AS</dt>
<dd>The maximum size of the process&#8217;s virtual memory (address space) in bytes.  This limit affects calls to brk(2), mmap(2) and mremap(2), which fail with the error ENOMEM upon exceeding this limit.  Also automatic stack expansion will fail (and generate a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)).  Since the value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.</dd>
<dt>RLIMIT_CORE</dt>
<dd>Maximum size of core file.  When 0 no core dump files are created. When non-zero, larger dumps are truncated to this size.</dd>
<dt>RLIMIT_CPU CPU</dt>
<dd>time limit in seconds.  When the process reaches the soft limit, it is sent a SIGXCPU signal.  The default action for this signal is to terminate the process.  However, the signal can be caught, and the handler can return control to the main program.  If the process continues to consume CPU time, it will be sent SIGXCPU once per second until the hard limit is reached, at which time it is sent SIGKILL. (This latter point describes Linux 2.2 through 2.6 behavior. Implementations vary in how they treat processes which continue to consume CPU time after reaching the soft limit.  Portable applications that need to catch this signal should perform an orderly termination upon first receipt of SIGXCPU.)</dd>
<dt>RLIMIT_DATA</dt>
<dd>The maximum size of the process&#8217;s data segment (initialized data, uninitialized data, and heap).  This limit affects calls to brk(2) and sbrk(2), which fail with the error ENOMEM upon encountering the soft limit of this resource.</dd>
<dt>RLIMIT_FSIZE</dt>
<dd>The maximum size of files that the process may create.  Attempts to extend a file beyond this limit result in delivery of a SIGXFSZ signal. By default, this signal terminates a process, but a process can catch this signal instead, in which case the relevant system call (e.g., write(2), truncate(2)) fails with the error EFBIG.</dd>
<dt>RLIMIT_LOCKS</dt>
<dd>(Early Linux 2.4 only) A limit on the combined number of flock(2) locks and fcntl(2) leases that this process may establish.</dd>
<dt>RLIMIT_MEMLOCK</dt>
<dd>The maximum number of bytes of memory that may be locked into RAM.  In effect this limit is rounded down to the nearest multiple of the system page size.  This limit affects mlock(2) and mlockall(2) and the mmap(2) MAP_LOCKED operation.  Since Linux 2.6.9 it also affects the shmctl(2) SHM_LOCK operation, where it sets a maximum on the total bytes in shared memory segments (see shmget(2)) that may be locked by the real user ID of the calling process.  The shmctl(2) SHM_LOCK locks are accounted for separately from the per-process memory locks established by mlock(2), mlockall(2), and mmap(2) MAP_LOCKED; a process can lock bytes up to this limit in each of these two categories.  In Linux kernels before 2.6.9, this limit controlled the amount of memory that could be locked by a privileged process.  Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process may lock, and this limit instead governs the amount of memory that an unprivileged process may lock.</dd>
<dt>RLIMIT_MSGQUEUE</dt>
<dd>(Since Linux 2.6.8) Specifies the limit on the number of bytes that can be allocated for POSIX message queues for the real user ID of the calling process.  This limit is enforced for mq_open(3).  Each message queue that the user creates counts (until it is removed) against this limit according to the formula:  <code>bytes = attr.mq_maxmsg * sizeof(struct msg_msg *) +             attr.mq_maxmsg * attr.mq_msgsize</code> where attr is the mq_attr structure specified as the fourth argument to mq_open(3).  The first addend in the formula, which includes sizeof(struct msg_msg *) (4 bytes on Linux/i386), ensures that the user cannot create an unlimited number of zero-length messages (such messages nevertheless each consume some system memory for bookkeeping overhead).</dd>
<dt>RLIMIT_NICE</dt>
<dd>(since Linux 2.6.12, but see BUGS below) Specifies a ceiling to which the process&#8217;s nice value can be raised using setpriority(2) or nice(2).  The actual ceiling for the nice value is calculated as 20 &#8211; rlim_cur.  (This strangeness occurs because negative numbers cannot be specified as resource limit values, since they typically have special meanings.  For example, RLIM_INFINITY typically is the same as -1.)</dd>
<dt>RLIMIT_NOFILE</dt>
<dd>Specifies a value one greater than the maximum file descriptor number that can be opened by this process.  Attempts (open(2), pipe(2), dup(2), etc.)  to exceed this limit yield the error EMFILE. (Historically, this limit was named RLIMIT_OFILE on BSD.)</dd>
<dt>RLIMIT_NPROC</dt>
<dd>The maximum number of processes (or, more precisely on Linux, threads) that can be created for the real user ID of the calling process.  Upon encountering this limit, fork(2) fails with the error EAGAIN.</dd>
<dt>RLIMIT_RSS</dt>
<dd>Specifies the limit (in pages) of the process&#8217;s resident set (the number of virtual pages resident in RAM).  This limit only has effect in Linux 2.4.x, x < 30, and there only affects calls to madvise(2) specifying MADV_WILLNEED.</dd>
<dt>RLIMIT_RTPRIO</dt>
<dd>(Since Linux 2.6.12, but see BUGS) Specifies a ceiling on the real-time priority that may be set for this process using sched_setscheduler(2) and sched_setparam(2).</dd>
<dt>RLIMIT_RTTIME</dt>
<dd>(Since Linux 2.6.25) Specifies a limit on the amount of CPU time that a process scheduled under a real-time scheduling policy may consume without making a blocking system call.  For the purpose of this limit, each time a process makes a blocking system call, the count of its consumed CPU time is reset to zero.  The CPU time count is not reset if the process continues trying to use the CPU but is preempted, its time slice expires, or it calls sched_yield(2). Upon reaching the soft limit, the process is sent a SIGXCPU signal.  If the process catches or ignores this signal and continues consuming CPU time, then SIGXCPU will be generated once each second until the hard limit is reached, at which point the process is sent a SIGKILL signal.  The intended use of this limit is to stop a runaway real-time process from locking up the system.</dd>
<dt>RLIMIT_SIGPENDING</dt>
<dd>(Since Linux 2.6.8) Specifies the limit on the number of signals that may be queued for the real user ID of the calling process.  Both standard and real-time signals are counted for the purpose of checking this limit.  However, the limit is only enforced for sigqueue(2); it is always possible to use kill(2) to queue one instance of any of the signals that are not already queued to the process.</dd>
<dt>RLIMIT_STACK</dt>
<dd>The maximum size of the process stack, in bytes.  Upon reaching this limit, a SIGSEGV signal is generated.  To handle this signal, a process must employ an alternate signal stack (sigaltstack(2)).</dd>
</dl>
<p><a id="ulimit-examples" name="ulimit-examples"></a></p>
<h4>ulimit Examples</h4>
<p>Turn off core dumps</p>
<pre>ulimit -S -c 0</pre>
<h2>More Reading</h2>
<ul>
<li>Please see the <a href="http://pagesperso-orange.fr/sebastien.godard/">SYSSTAT Utilities Home for more performance monitoring tools</a> like sar, sadf, mpstat, iostat, pidstat and sa tools.</li>
<li><a href="http://gaarai.com/2009/03/06/multitasking-from-the-linux-command-line-plus-process-prioritization/">Multitasking from the Linux Command Line + Process Prioritization</a></li>
</ul>
<h2>Man Pages</h2>
<ol>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man2/sched_setscheduler.2.html">sched_setscheduler</a></li>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man7/cpuset.7.html">cpuset</a></li>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.html">signal</a></li>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man2/getrlimit.2.html">getrlimit</a></li>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man3/ulimit.3.html">ulimit</a></li>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man2/ioprio_get.2.html">ioprio_get</a></li>
<li><a href="http://www.kernel.org/doc/man-pages/online/pages/man2/ioprio_set.2.html">ioprio_set</a></li>
</ol>
<h2>Kernel Documentation</h2>
<ul>
<li><a href='/wp-content/uploads/2009/08/sched-stats.txt'>information on schedstats (Linux Scheduler Statistics)</a></li>
<li><a href='/wp-content/uploads/2009/08/sched-rt-group.txt'>real-time group scheduling</a></li>
<li><a href='/wp-content/uploads/2009/08/sched-nice-design.txt'>How and why the scheduler&#8217;s nice levels are implemented</a></li>
<li><a href='/wp-content/uploads/2009/08/sched-domains.txt'>information on scheduling domains</a></li>
<li><a href='/wp-content/uploads/2009/08/sched-design-CFS.txt'>goals, design and implementation of the Complete Fair Scheduler</a></li>
</ul>
<h2>Future Discussions:</h2>
<p><a href="http://www.cuddletech.com/blog/pivot/entry.php?id=820">IO Benchmarking: How, Why and With What</a></p>
<p><a href="http://www.askapache.com/linux-unix/optimize-nice-ionice.html">Optimizing Servers and Processes for Speed with ionice, nice, ulimit</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/linux-unix/optimize-nice-ionice.html/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Advanced WordPress wp-config.php Tweaks</title>
		<link>http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html</link>
		<comments>http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html#comments</comments>
		<pubDate>Sat, 03 Oct 2009 07:23:37 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Server Administration]]></category>
		<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Web Design]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[Webmaster]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress Plugins]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[admin]]></category>
		<category><![CDATA[advanced]]></category>
		<category><![CDATA[Cookies]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[phpinfo]]></category>
		<category><![CDATA[wp-config.php]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=3341</guid>
		<description><![CDATA[<p>The bottom line for this article is that I want to make WordPress as fast, secure, and easy to install, run, and manage because I am using it more and more for client production sites, I will work for days in order to solve an issue so that I never have to spend time on that issue again. Time is money in this industry and that is ultimately (time) what there is to gain by tweaking WordPress.</p>

<p class="cnote"><strong>Note:</strong> I spent no time on readability, this is primarily a read the code and figure it out article.. This is for advanced users looking for a reference or discussion and for those of you looking to advance.  Feedback would be great <em>if you make it that far..</em></p>]]></description>
			<content:encoded><![CDATA[<p>The bottom line for this article is that I want to make WordPress as fast, secure, and easy to install, run, and manage because I am using it more and more for client production sites, I will work for days in order to solve an issue so that I never have to spend time on that issue again. Time is money in this industry and that is ultimately (time) what there is to gain by tweaking WordPress.</p>
<p class="cnote"><strong>Note:</strong> I spent no time on readability, this is primarily a read the code and figure it out article.. This is for advanced users looking for a reference or discussion and for those of you looking to advance.  Feedback would be great <em>if you make it that far..</em></p>
<p>For a better handle on the way I like to structure web site directories, see <a href="http://www.askapache.com/htaccess/optimize-website-files-cache-security.html">Optimize a Website for Speed, Security, and Easy Management</a> but note it is a bit outdated compared to what I&#8217;m doing now.  I don&#8217;t have the luxury of using only one type of server, or hosting provider anymore, so I have been working towards making things even more portable in order to move from host to host from server to server without issues i.e. my portable <a href="http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html">.bash_profile</a>.</p>
<p>So I&#8217;ve been basically experimenting various ways to accomplish that and thought I would share what I am currently doing for my benefit and hopefully get some input.  All of my WP installs run the development version, and one main idea with my setups is that upgrading is automated.  So I really keep the WordPress install clean and use plugins and wp-config.php to do all the customization.</p>
<ul>
<li>Portability &#8211; Hands-free upgrades and easy to move</li>
<li>Security &#8211; Additional security and protection</li>
<li>Speed &#8211; Less CPU and Disk I/O</li>
<li>Customization &#8211; All my favorite customizations</li>
</ul>
<h2>wp-config.php</h2>
<p>These are the main settings I use.. Seriously this is more like an interactive article, because to understand it you will need to do some code grepping.  You may want to grab a jolt.</p>
<h3>ASKAPACHE_ROOT</h3>
<p>The ASKAPACHE_ROOT variable is just a better way for me to be able to include and access all the different files in my site tree.  For instance, in my non-wp php files, I can do this:</p>
<pre>
!defined(&#039;ASKAPACHE_ROOT&#039;) &#038;&#038; require $_SERVER[&#039;DOCUMENT_ROOT&#039;] . &#039;/wp-config.php&#039;;
include(ASKAPACHE_ROOT . &#039;/includes/custom-download.inc.php&#039;);
</pre>
<h3>ASKAPACHE_LOCK</h3>
<p>This is one of my all-time favorite hacks, that I think is one of the most useful methods I employ as a web developer.  This allows me to use far-future-expire headers for optimum caching, while still forcing browsers to re-validate every day or so automatically, or forcing them to re-validate whenever I change the suffix.  This takes advantage of the <a href="http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html">mod_rewrite trick</a> that I use on EVERY site I run, definately worth learning. Because I practice best-practice web-standards, for every web site I create a single css file and javascript file, which I then add to the template like:</p>
<pre>
&lt;link rel="stylesheet" type="text/css" media="all" href="http://z.askapache.com/c/apache-0&lt;?php echo ASKAPACHE_LOCK?&gt;.css" /&gt;
&lt;script src="http://z.askapache.com/j/apache-0&lt;?php echo ASKAPACHE_LOCK;?&gt;.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>
<pre>
&lt;?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information by
 * visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don&#039;t have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 *
 * @package WordPress
 */
/* http://codex.wordpress.org/Editing_wp-config.php */
&nbsp;
/** /home/liet/askapache.com */
!defined(&#039;ASKAPACHE_ROOT&#039;) &#038;&#038; define(&#039;ASKAPACHE_ROOT&#039;, str_replace(&#039;/htdocs&#039;,&#039;&#039;, $_SERVER[&#039;DOCUMENT_ROOT&#039;]));
&nbsp;
/** The 008 at the end is for manual tweaking.  time() returns seconds since &#039;00:00:00 1970-01-01 UTC&#039;. */
// http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html
!defined(&#039;ASKAPACHE_LOCK&#039;) &#038;&#038; define(ASKAPACHE_LOCK&#039;, substr(time(),0,5).&#039;008&#039;); // 12533001
&nbsp;
/** absolute path to the Wordpress directory */
!defined(&#039;ABSPATH&#039;) &#038;&#038; define(&#039;ABSPATH&#039;, ASKAPACHE_ROOT .&#039;/htdocs/&#039;);
&nbsp;
/**
 * WP_SITEURL, defined since WordPress Version 2.2, allows the WordPress address (URL) to be defined. The valued defined is the address where your WordPress core files reside.
 * It should include the http:// part too. Do not put a slash "/" at the end.
 * Setting this value in wp-config.php overrides the wp_options table value for siteurl and disables the WordPress address (URL) field in the Administration &gt; Settings &gt; General panel.
 */
!defined(&#039;WP_SITEURL&#039;) &#038;&#038; define(&#039;WP_SITEURL&#039;, &#039;http://&#039;.$_SERVER[&#039;SERVER_NAME&#039;]);
&nbsp;
/**
 * WP_HOME is another wp-config.php option added in WordPress Version 2.2. Similar to WP_SITEURL,
 * WP_HOME overrides the wp_options table value for home but does not change it permanently.
 * home is the address you want people to type in their browser to reach your WordPress blog. It should include the http:// part. Also, do not put a slash "/" at the end.
 */
!defined(&#039;WP_HOME&#039;) &#038;&#038; define(&#039;WP_HOME&#039;, WP_SITEURL);
&nbsp;
/** no trailing slash, full paths only */
!defined(&#039;WP_CONTENT_DIR&#039;) &#038;&#038; define( &#039;WP_CONTENT_DIR&#039;, ABSPATH . &#039;wp-content&#039; );
&nbsp;
// full url - WP_CONTENT_DIR is defined further up
!defined(&#039;WP_CONTENT_URL&#039;) &#038;&#038; define( &#039;WP_CONTENT_URL&#039;, WP_SITEURL . &#039;/wp-content&#039;);
&nbsp;
/** Allows for the plugins directory to be moved from the default location. @since 2.6.0 */
// full path, no trailing slash
!defined(&#039;WP_PLUGIN_DIR&#039;) &#038;&#038; define( &#039;WP_PLUGIN_DIR&#039;, WP_CONTENT_DIR . &#039;/plugins&#039; );
&nbsp;
/** Allows for the plugins directory to be moved from the default location. @since 2.6.0 */
// full url, no trailing slash
!defined(&#039;WP_PLUGIN_URL&#039;) &#038;&#038; define( &#039;WP_PLUGIN_URL&#039;, WP_CONTENT_URL . &#039;/plugins&#039; );
&nbsp;
/** Allows for the plugins directory to be moved from the default location. @since 2.1.0 */
// Relative to ABSPATH.  For back compat.
//!defined(&#039;PLUGINDIR&#039;) &#038;&#038; define( &#039;PLUGINDIR&#039;, &#039;wp-content/plugins&#039; );
&nbsp;
/** Number of autosaves to save. TRUE is default and enables post revisions, FALSE disables revisions completely. */
!defined(&#039;WP_POST_REVISIONS&#039;) &#038;&#038; define(&#039;WP_POST_REVISIONS&#039;, 150);
&nbsp;
/* ini_set(&#039;memory_limit&#039;, WP_MEMORY_LIMIT); */
!defined(&#039;WP_MEMORY_LIMIT&#039;) &#038;&#038; define(&#039;WP_MEMORY_LIMIT&#039;, &#039;64M&#039;);
&nbsp;
/** Only check at this interval for new messages. Default is 5min */
/** @since 2.9  */
!defined(&#039;WP_MAIL_INTERVAL&#039;) &#038;&#038; define(&#039;WP_MAIL_INTERVAL&#039;, 3600); // 1 hour
&nbsp;
/** Saves updated post values to post from edit window every x seconds. (default 60)
 * When editing a post, WordPress uses Ajax to auto-save revisions to the post as you edit. You may want to increase this setting for longer delays in between auto-saves, or decrease the setting to make sure you never lose changes.
 * @since 2.5.0 */
!defined( &#039;AUTOSAVE_INTERVAL&#039; ) &#038;&#038; define( &#039;AUTOSAVE_INTERVAL&#039;, 60 );
&nbsp;
/** @since 2.9.0  */
/** Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS. */
!defined( &#039;EMPTY_TRASH_DAYS&#039; ) &#038;&#038; define( &#039;EMPTY_TRASH_DAYS&#039;, 300 );
</pre>
<hr class="C" />
<h2>Debugging WordPress</h2>
<p>One of my secrets for getting really good at this stuff is to master debugging.  There is really not ever a time when I am working on a site that I don&#8217;t have <a href="http://www.askapache.com/security/elite-log-file-scrolling-with-color-syntax.html">color-highlighted logs scrolling automatically in an ssh window</a>.  It&#8217;s really almost impossible to fix problems with wordpress or do any kind of advanced anything without being able to view debugging info.  At first I relied heavily on a <a href="http://www.askapache.com/php/custom-phpini-tips-and-tricks.html">custom php.ini</a> being available on the server, but after having to deal with many hosts who don&#8217;t allow <code>php.ini</code> files I now rely completely on setting values using <a href="http://php.net/manual/en/function.ini-set.php">ini_set</a> for ultimate portability. Detailed towards the end of this article and is also included in this <code>wp-config.php</code></p>
<pre>
/**#@+
 * DEBUGGING STUFF
 */
/** display of notices during development. if false, error_reporting is E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR otherwise E_ALL */
!defined(&#039;WP_DEBUG&#039;) &#038;&#038; define(&#039;WP_DEBUG&#039;, false);
&nbsp;
/** The SAVEQUERIES definition saves the database queries to a array and that array can be displayed to help analyze those queries.
 *  The information saves each query, what function called it, and how long that query took to execute.  */
!defined(&#039;SAVE_QUERIES&#039;) &#038;&#038; define(&#039;SAVE_QUERIES&#039;, WP_DEBUG);
&nbsp;
!defined(&#039;ACTION_DEBUG&#039;) &#038;&#038; define(&#039;ACTION_DEBUG&#039;, WP_DEBUG);
&nbsp;
/** This will allow you to edit the scriptname.dev.js files in the wp-includes/js and wp-admin/js directories.  */
!defined(&#039;SCRIPT_DEBUG&#039;) &#038;&#038; define(&#039;SCRIPT_DEBUG&#039;, WP_DEBUG);

&nbsp;
/** Add define(&#039;WP_DEBUG_LOG&#039;, true); to enable php debug logging to WP_CONTENT_DIR/debug.log */
//!defined(&#039;WP_DEBUG_LOG&#039;) &#038;&#038; define(&#039;WP_DEBUG_LOG&#039;, true);
&nbsp;
/** This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.
 *  Add define(&#039;WP_DEBUG_DISPLAY&#039;, false); to wp-config.php to use the globally configured setting for display_errors and not force it to On */
!defined(&#039;WP_DEBUG_DISPLAY&#039;) &#038;&#038; define(&#039;WP_DEBUG_DISPLAY&#039;, false);
</pre>
<hr class="C" />
<h2>Ultimate Security Tweaks</h2>
<p>Well, ultimate for WP&#8217;s built-in keys and password functions, this is all for wp-config.php keep in mind.  This is a very neccessary and recommended step, and is one of the only things I modify for each new installation.</p>
<h3>Security KEYS</h3>
<p>If like me you are familiar with password-cracking software like John the ripper, rainbow hash tables, l0pht-crack, etc.. then you will like to know that you can specify your own keys and salts for the encryption used by WP.  They are <code>AUTH_KEY</code>, <code>AUTH_SALT</code>, <code>SECURE_AUTH_KEY</code>, <code>SECURE_AUTH_SALT</code>, <code>LOGGED_IN_KEY</code>, <code>LOGGED_IN_SALT</code>, <code>NONCE_KEY</code>, <code>NONCE_SALT</code>,  <code>SECRET_KEY</code> and <code>SECRET_SALT</code>.</p>
<p>A random and long key gives you better encryption, and exponentially increasing that is using a random and long salt for the encryption.  Encryptions with known salts are incredibly easy to decrypt compared to encryptions with secure salts, because the salt + key individually need to be guessed in order to find a matching hash, vs. just the key if the salt is known.  See: <a href="http://www.askapache.com/security/locating-weak-passwords.html">Locating weak passwords</a>.</p>
<blockquote>
<p>A secret key is a hashing salt which makes your site harder to hack and access harder to crack by adding random elements to the password.</p>
<p>In simple terms, a secret key is a password with elements that make it harder to generate enough options to break through your security barriers. A password like &#8220;password&#8221; or &#8220;test&#8221; is simple and easily broken. A random, unpredictable password such as &#8220;88a7da62429ba6ad3cb3c76a09641fc&#8221; takes years to come up with the right combination.</p>
</blockquote>
<p>For more information on the technical background and breakdown of secret keys and secure passwords, see: </p>
<ul>
<li><a href="http://wordpress.org/support/topic/170987">WordPress Support Forum &#8211; HOWTO: Set up secret keys in WordPress 2.6+</a></li>
<li><a href="http://en.wikipedia.org/wiki/Password_cracking">Wikipedia&#8217;s explanation of Password Cracking</a></li>
</ul>
<p>I like to use the <a href="https://api.wordpress.org/secret-key/1.1/">WordPress.org secret-key service</a> 4 times.  That&#8217;s because for each key and salt I like to do: (1 key from api +random keyboard input+1 key from api).</p>
<pre>
/**#@+
 * Authentication Unique Keys.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies.
 * This will force all users to have to log in again.
 *
 * @since 2.6.0
 *
 * Get salt to add to hashes to help prevent attacks.
 *
 * The secret key is located in two places: the database in case the secret key
 * isn&#039;t defined in the second place, which is in the wp-config.php file. If you
 * are going to set the secret key, then you must do so in the wp-config.php
 * file.
 *
 * The secret key in the database is randomly generated and will be appended to
 * the secret key that is in wp-config.php file in some instances. It is
 * important to have the secret key defined or changed in wp-config.php.
 *
 * If you have installed WordPress 2.5 or later, then you will have the
 * SECRET_KEY defined in the wp-config.php already. You will want to change the
 * value in it because hackers will know what it is. If you have upgraded to
 * WordPress 2.5 or later version from a version before WordPress 2.5, then you
 * should add the constant to your wp-config.php file.
 *
 * Below is an example of how the SECRET_KEY constant is defined with a value.
 * You must not copy the below example and paste into your wp-config.php. If you
 * need an example, then you can have a
 * {@link https://api.wordpress.org/secret-key/1.1/ secret key created} for you.
 *
 * Salting passwords helps against tools which has stored hashed values of
 * common dictionary strings. The added values makes it harder to crack if given
 * salt string is not weak.
 *
 * @since 2.5
 * @link https://api.wordpress.org/secret-key/1.1/ Create a Secret Key for wp-config.php
 *
 * @return string Salt value from either &#039;SECRET_KEY&#039; or &#039;secret&#039; option
 */
define(&#039;AUTH_KEY&#039;,        &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?p[B+GR{@&gt;{Yq`c|LnG;dvq#| %OA_cbBSU6,rICC1o/c)-|&#039;);
define(&#039;SECURE_AUTH_KEY&#039;, &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[Bb15baar8&#038;R-r&lt;[T|?(xhJJABGq+Ux+U$)-Hltp/&#039;);
define(&#039;LOGGED_IN_KEY&#039;,   &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[B&lt;5n6DG|YWnJ9tY2!M1L)`{-$LW~~Ia%.uCbn!P. 41o2$Z$4&#039;);
define(&#039;NONCE_KEY&#039;,       &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[Bgu&lt;wM*zewR0.{+m:bmrB?wj!B,4]Wo+4 Avk ApR-D?E&#039;);
define(&#039;SECRET_KEY&#039;,     &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[B52ugH6muE9r4._iZwoYKUybrqLPpv|d Xr+|yrqhUE&#039;);
&nbsp;
define(&#039;AUTH_SALT&#039;,        &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdm~Ky%+%~PPa5b YEmDI%U[W!-B&#039;);
define(&#039;SECURE_AUTH_SALT&#039;, &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdmad/7o6.AU3%9o-|Kqm]+eUqr-n~:ag&#039;);
define(&#039;LOGGED_IN_SALT&#039;,   &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdmsLiCv@KJ{#wd(?qe(KcH3!&#039;);
define(&#039;NONCE_SALT&#039;,       &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdmG9&gt;+wm 2)bS0Pd_+1rx0brX]ND8|&#039;);
define(&#039;SECRET_SALT&#039;,      &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdm2&lt;&gt;))U|sty)+4vpWooKls/^[vN&#039;);
/**#@-*/
</pre>
<hr class="C" />
<h2>Using SSL for Admin and Login</h2>
<p>SSL is kinda required from my point of view, it is just way to easy to sniff data off the wire otherwise.  At least with SSL you force them to use tools like burpsuite, paros proxy, webscarab, etc..</p>
<pre>
/** @since 2.6.0  */
!defined(&#039;FORCE_SSL_ADMIN&#039;) &#038;&#038; define(&#039;FORCE_SSL_ADMIN&#039;, true);
&nbsp;
/** @since 2.6.0  */
!defined(&#039;FORCE_SSL_LOGIN&#039;) &#038;&#038; define(&#039;FORCE_SSL_LOGIN&#039;, true);
</pre>
<h3>Mod_Rewrite to Force SSL</h3>
<p>This is pretty cool, it forces non-https for all urls except for /wp-admin and wp-login.php, which both require https.  It also checks for the logged_in_cookie, and if that is present in the request then it doesn't force non-https.  Kinda confusing if you don't have a <a href="http://www.askapache.com/htaccess/mod_rewrite-variables-cheatsheet.html">mod_rewrite cheatsheet</a>.</p>
<pre>
RewriteCond %{THE_REQUEST} ^$ [OR]
RewriteCond %{REQUEST_URI} ^/(wp-admin|wp-login\.php).*$ [NC,OR]
RewriteCond %{HTTP_COOKIE} ^.*wp_li_sadfsdfasdf11b361cdsdfasdfasd=.*$ [NC]
RewriteRule .* - [S=1]
&nbsp;
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
&nbsp;
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(wp-admin/.*|wp-login\.php.*)\ HTTP/ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</pre>
<hr class="C" />
<h2>File System Permissions</h2>
<p><a class="IFR" href="http://www.askapache.com/security/chmod-umask-fileperms-stat-tricks.html"><img src="/wp-content/uploads/2008/11/danger-chmod-screenshot.png" alt="chmod, umask, file permissions test" title="chmod, umask, file permissions test" /></a>You can get a basic and solid intro on file permissions by reading: <a href="http://codex.wordpress.org/Changing_File_Permissions">Changing File Permissions</a>, or you can check out some of my <a href="http://www.askapache.com/security/chmod-umask-fileperms-stat-tricks.html">file permission research</a>.<br class="C" /></p>
<pre>
/** The permissions as octal number, usually 0644 for files, 0755 for dirs.
 *  http://codex.wordpress.org/Changing_File_Permissions
 *  if ( !$wp_filesystem-&gt;mkdir($remote_destination, FS_CHMOD_DIR) )
 */
!defined(&#039;FS_CHMOD_DIR&#039;) &#038;&#038; define(&#039;FS_CHMOD_DIR&#039;, (0755 &#038; ~ umask()));
!defined(&#039;FS_CHMOD_FILE&#039;) &#038;&#038; define(&#039;FS_CHMOD_FILE&#039;, (0644 &#038; ~ umask()));
/**#@-*/
&nbsp;
/** Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default. */
//stream_set_timeout( $stream, FS_TIMEOUT );
//!defined(&#039;FS_TIMEOUT&#039;) &#038;&#038; define(&#039;FS_TIMEOUT&#039;, 30);
&nbsp;
//$this-&gt;link = @ftp_connect($this-&gt;options[&#039;hostname&#039;], $this-&gt;options[&#039;port&#039;], FS_CONNECT_TIMEOUT);
//!defined(&#039;FS_CONNECT_TIMEOUT&#039;) &#038;&#038; define(&#039;FS_CONNECT_TIMEOUT&#039;, 30);
&nbsp;
// function get_filesystem_method($args = array(), $context = false) {
//  $method = defined(&#039;FS_METHOD&#039;) ? FS_METHOD : false; //Please ensure that this is either &#039;direct&#039;, &#039;ssh&#039;, &#039;ftpext&#039; or &#039;ftpsockets&#039;
//!defined(&#039;FS_METHOD&#039;) &#038;&#038; define(&#039;FS_METHOD&#039;, &#039;direct&#039;);
&nbsp;
/** These methods for the WordPress core, plugin, and theme upgrades try to determine the WordPress path, as reported by PHP, but symlink trickery can sometimes
 * &#039;muck this up&#039; so if you know the paths to the various folders on the server, as seen via your FTP user, you can manually define them in the wp-config.php file.
 * FS_METHOD forces the filesystem method. It should only be "direct", "ssh", "ftpext", or "ftpsockets".
 * FTP_BASE is the full path to the "base" folder of the WordPress installation.
 * FTP_CONTENT_DIR is the full path to the wp-content folder of the WordPress installation.
 * FTP_PLUGIN_DIR is the full path to the plugins folder of the WordPress installation.
 * FTP_PUBKEY is the full path to your SSH public key.
 * FTP_PRIKEY is the full path to your SSH private key.
 * FTP_USER is either user FTP or SSH username. Most likely these are the same, but use the appropriate one for the type of update you wish to do.
 * FTP_PASS is the password for the username entered for FTP_USER. If you are using SSH public key authentication this can be omitted.
 * FTP_HOST is the hostname:port combination for your SSH/FTP server. The standard FTP port is 21 and the standard SSH port is 22.
 */
//define(&#039;FS_METHOD&#039;, &#039;ftpext&#039;);
//define(&#039;FTP_BASE&#039;, &#039;/path/to/wordpress/&#039;);
//define(&#039;FTP_CONTENT_DIR&#039;, &#039;/path/to/wordpress/wp-content/&#039;);
//define(&#039;FTP_PLUGIN_DIR &#039;, &#039;/path/to/wordpress/wp-content/plugins/&#039;);
//define(&#039;FTP_PUBKEY&#039;, &#039;/home/username/.ssh/id_rsa.pub&#039;);
//define(&#039;FTP_PRIKEY&#039;, &#039;/home/username/.ssh/id_rsa&#039;);
//define(&#039;FTP_USER&#039;, &#039;username&#039;);
//define(&#039;FTP_PASS&#039;, &#039;password&#039;);
//define(&#039;FTP_HOST&#039;, &#039;ftp.example.org:21&#039;);
&nbsp;
/**
 * Block requests through the proxy.
 *
 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
 * prevent plugins from working and core functionality, if you don&#039;t include api.wordpress.org.
 *
 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL in your wp-config.php file
 * and this will only allow localhost and your blog to make requests.
 * The constant WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
 *
 * @since 2.8.0
 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
/** @since 2.9  */
//!defined(&#039;WP_HTTP_BLOCK_EXTERNAL&#039;) &#038;&#038; define( &#039;WP_HTTP_BLOCK_EXTERNAL&#039;, false );
&nbsp;
/*
 * The constant WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
 *
 * @since 2.8.0
 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
 * $accessible_hosts = preg_split(&#039;|,\s*|&#039;, WP_ACCESSIBLE_HOSTS);
 * return !in_array( $check[&#039;host&#039;], $accessible_hosts ); //Inverse logic, If its in the array, then we can&#039;t access it.
 */
//!defined(&#039;WP_ACCESSIBLE_HOSTS&#039;) &#038;&#038; define( &#039;WP_ACCESSIBLE_HOSTS&#039;, &#039;askapache.com,askapache.org&#039; );
</pre>
<hr class="C" />
<h3>Cookies!</h3>
<p>There&#8217;s always a little comfort in having non-default cookies for security (against auto-bots), and using shorter names also means smaller HTTP Packets.</p>
<p>The <code>$cookie_hash</code> is my hack to get around the fact that <code>COOKIEHASH</code> isn&#8217;t definable in <code>wp-config</code>.</p>
<pre>
/**#@+
 * COOKIES
 * Used to guarantee unique hash cookies @since 1.5 */
$cookie_hash=md5(WP_SITEURL);
&nbsp;
/** Set a cookie now to see if they are supported by the browser.
 * setcookie(TEST_COOKIE, &#039;WP Cookie check&#039;, 0, COOKIEPATH, COOKIE_DOMAIN);
 * @since 2.3.0 */
!defined(&#039;TEST_COOKIE&#039;) &#038;&#038; define(&#039;TEST_COOKIE&#039;, &#039;wp_tc&#039;);
&nbsp;
/* @since 2.6.0 */
!defined(&#039;LOGGED_IN_COOKIE&#039;) &#038;&#038; define(&#039;LOGGED_IN_COOKIE&#039;, &#039;wp_li_&#039; . $cookie_hash);
&nbsp;
/* @since 2.6.0 */
!defined(&#039;SECURE_AUTH_COOKIE&#039;) &#038;&#038; define(&#039;SECURE_AUTH_COOKIE&#039;, &#039;wp_sa_&#039; . $cookie_hash);
&nbsp;
/* @since 2.5.0 */
!defined(&#039;AUTH_COOKIE&#039;) &#038;&#038; define(&#039;AUTH_COOKIE&#039;, &#039;wp_a_&#039; . $cookie_hash);
&nbsp;
/* @since 2.0.0 */
!defined(&#039;PASS_COOKIE&#039;) &#038;&#038; define(&#039;PASS_COOKIE&#039;, &#039;wp_p_&#039; . $cookie_hash);
&nbsp;
/* @since 2.0.0 */
!defined(&#039;USER_COOKIE&#039;) &#038;&#038; define(&#039;USER_COOKIE&#039;, &#039;wp_u_&#039; . $cookie_hash);
&nbsp;
/* ok unset this var, its not needed as COOKIEHASH will have this value, but is not definable in wp-config.php */
unset($cookie_hash);
&nbsp;
/** @since 1.2.0 */
!defined(&#039;COOKIEPATH&#039;) &#038;&#038; define(&#039;COOKIEPATH&#039;, preg_replace(&#039;|https?://[^/]+|i&#039;, &#039;&#039;, WP_HOME . &#039;/&#039; ) );
&nbsp;
/** @since 1.5.0 */
!defined(&#039;SITECOOKIEPATH&#039;) &#038;&#038; define(&#039;SITECOOKIEPATH&#039;, preg_replace(&#039;|https?://[^/]+|i&#039;, &#039;&#039;, WP_SITEURL . &#039;/&#039; ) );
&nbsp;
/** @since 2.6.0 */
!defined(&#039;ADMIN_COOKIE_PATH&#039;) &#038;&#038; define( &#039;ADMIN_COOKIE_PATH&#039;, SITECOOKIEPATH . &#039;wp-admin&#039; );
&nbsp;
/** @since 2.6.0 */
!defined(&#039;PLUGINS_COOKIE_PATH&#039;) &#038;&#038; define( &#039;PLUGINS_COOKIE_PATH&#039;, preg_replace(&#039;|https?://[^/]+|i&#039;, &#039;&#039;, WP_PLUGIN_URL)  );
&nbsp;
/** @since 2.0.0 */
!defined(&#039;COOKIE_DOMAIN&#039;) &#038;&#038; define(&#039;COOKIE_DOMAIN&#039;, $_SERVER[&#039;SERVER_NAME&#039;]);
</pre>
<hr class="C" />
<pre>
/**
  * The WP_CACHE setting, if true, includes the wp-content/advanced-cache.php script, when executing wp-settings.php.
  * For an advanced caching plugin to use, static because you would only want one
  * if ( defined(&#039;WP_CACHE&#039;) )@include WP_CONTENT_DIR . &#039;/advanced-cache.php&#039;;
  */
!defined(&#039;WP_CACHE&#039;) &#038;&#038; define(&#039;WP_CACHE&#039;, true);
&nbsp;
/** WordPress Localized Language, defaults to en_US.
 *
 * Change this to localize WordPress.  A corresponding MO file for the chosen
 * language must be installed to wp-content/languages. For example, install
 * de.mo to wp-content/languages and set WPLANG to &#039;de&#039; to enable German
 * language support. */
!defined(&#039;WPLANG&#039;) &#038;&#038; define (&#039;WPLANG&#039;, &#039;en_US&#039;);
&nbsp;
/** Stores the location of the language directory. First looks for language folder in WP_CONTENT_DIR
 *   and uses that folder if it exists. Or it uses the "languages" folder in WPINC. @since 2.1.0 */
//!defined(&#039;WP_LANG_DIR&#039;) &#038;&#038; define(&#039;WP_LANG_DIR&#039;, ABSPATH . WPINC . &#039;/languages&#039;);
&nbsp;
/** LANGDIR defines what directory the WPLANG .mo file resides. If LANGDIR is not defined WordPress looks first to wp-content/languages and then wp-includes/languages for the .mo defined by WPLANG file.  Old static relative path maintained for limited backwards compatibility - won&#039;t work in some cases*/
//!defined(&#039;LANGDIR&#039;) &#038;&#038; define(&#039;LANGDIR&#039;, &#039;wp-content/languages&#039;);
&nbsp;
/** Stores the location of the WordPress directory of functions, classes, and core content. @since 1.0.0 */
//!defined(&#039;WPINC&#039;) &#038;&#038; define(&#039;WPINC&#039;, &#039;wp-includes&#039;);
</pre>
<hr class="C" />
<h2>WPMU Stuff</h2>
<p>I personally don&#8217;t use.</p>
<pre>
/** Allows for the mu-plugins directory to be moved from the default location. @since 2.8.0 */
//!defined(&#039;WPMU_PLUGIN_DIR&#039;) &#038;&#038; define( &#039;WPMU_PLUGIN_DIR&#039;, WP_CONTENT_DIR . &#039;/mu-plugins&#039; ); // full path, no trailing slash
&nbsp;
/** Allows for the mu-plugins directory to be moved from the default location. @since 2.8.0 */
//!defined(&#039;WPMU_PLUGIN_URL&#039;) &#038;&#038; define( &#039;WPMU_PLUGIN_URL&#039;, WP_CONTENT_URL . &#039;/mu-plugins&#039; ); // full url, no trailing slash
&nbsp;
/** Allows for the mu-plugins directory to be moved from the default location. @since 2.8.0 */
//!defined( &#039;MUPLUGINDIR&#039; ) &#038;&#038; define( &#039;MUPLUGINDIR&#039;, &#039;wp-content/mu-plugins&#039; ); // Relative to ABSPATH.  For back compat.
</pre>
<hr class="C" />
<h2>WordPress Database</h2>
<p>This is usually the only thing I have to manually edit when creating a new site, unless I just use the same DB and modify the $table_prefix, (farther down). I run everything I possibly can in UTF-8, but if you don&#8217;t already know alot about character sets, wow it is one of the most confusing things so you may want to save learning about that topic for another day.  Otherwise the following are helpful (<em>and show how confusing character sets are!</em>)</p>
<ul>
<li><a href="http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html">Character Sets and Collations MySQL Support</a></li>
<li><a href="http://codex.wordpress.org/Converting_Database_Character_Sets">Converting Database Character Sets</a></li>
<li><a href="http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html">UTF-8 character sets</a> (<a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>)</li>
</ul>
<p>If you ever setup WP to use the builtin membership features, make sure you learn about the <code>CUSTOM_USER_TABLE</code> and <code>CUSTOM_USER_META_TABLE</code> constants, I&#8217;ve found them very helpful.</p>
<pre>
/**#@+
 * MySQL settings
 */
/** The name of the database for WordPress */
define(&#039;DB_NAME&#039;, &#039;askapachewpblog75&#039;);
&nbsp;
/** The username to access the database */
define(&#039;DB_USER&#039;, &#039;askapache245d&#039;);
&nbsp;
/** The password for the username to access the database */
define(&#039;DB_PASSWORD&#039;, &#039;asdfklj2340&#039;);
&nbsp;
/** The hostname to connect to the database at */
define(&#039;DB_HOST&#039;, &#039;mysql.askapache.com&#039;);
&nbsp;
/** The charset of the database */
define(&#039;DB_CHARSET&#039;, &#039;utf8&#039;);
&nbsp;
/** The collation of the database */
define(&#039;DB_COLLATE&#039;, &#039;utf8_general_ci&#039;);
</pre>
<hr class="C" />
<h2>$table_prefix</h2>
<p>The <code>$table_prefix</code> is the value placed in the front of your database tables. Change the value if you want to use something other than wp_ for your database prefix. Typically this is changed if you are <a href="http://codex.wordpress.org/Installing_Multiple_Blogs">installing multiple WordPress blogs</a> in the same database, and also for enhanced security.</p>
<p>Its a safe and good idea to change this value pre-installation to add more security to your WordPress blog. Exploits attempted against your WordPress blog by malicious crackers often are built with the premise that your blog uses the prefix wp_, by changing the value you mitigate some attack vectors. </p>
<pre>
/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = &#039;ar15_&#039;;
&nbsp;
/** CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE are used to designated that the user and usermeta tables normally utilized by WordPress are not used, instead these values/tables are used to store your user information. */
//!defined(&#039;CUSTOM_USER_TABLE&#039;) &#038;&#038; define(&#039;CUSTOM_USER_TABLE&#039;, $table_prefix . &#039;my_users&#039;);
//!defined(&#039;CUSTOM_USER_META_TABLE&#039;) &#038;&#038; define(&#039;CUSTOM_USER_META_TABLE&#039;, $table_prefix . &#039;my_usermeta&#039;);
</pre>
<h2>Setup PHP Ini Settings</h2>
<pre>
&nbsp;
/** Turns the output of errors on or off, you really never want this on, you should only view errors by reading the log file. */
ini_set(&#039;display_errors&#039;, WP_DEBUG_DISPLAY);
&nbsp;
/** Tells whether script error messages should be logged to the server&#039;s error log or error_log. */
ini_set(&#039;log_errors&#039;, &#039;On&#039;);
&nbsp;
/** http://us.php.net/manual/en/timezones.php */
ini_set(&#039;date.timezone&#039;, &#039;America/Indianapolis&#039;);
&nbsp;
/** Where to log php errors */
ini_set(&#039;error_log&#039;, ASKAPACHE_ROOT . &#039;/logs/php_error.log&#039;);
&nbsp;
/** Set the memory limit, otherwise defaults to &#039;32M&#039; */
ini_set(&#039;memory_limit&#039;, WP_MEMORY_LIMIT);
</pre>
<h2>Sessions are slow</h2>
<p>So I only use sessions when I have a specific use&#8230; In this case I need sessions only when one of the tools in the /online-tools/ directory is being used.  And that is for the <a href="http://www.askapache.com/security/php-captcha-anti-spam-example.html">captcha image</a>.  In the future I won&#8217;t ever use sessions.</p>
<pre>
if(preg_match( &#039;#^/online-tools/#&#039;,$_SERVER[&#039;REQUEST_URI&#039;])) session_start();
</pre>
<h2>Include Custom Files</h2>
<p>Sure you could use the my-hacks.php that WP allows, or you can just stick your functions in your <code>TEMPLATEPATH/functions.php</code> file, but they are executed only after the wp-settings.php file, which may be too late for your file.</p>
<p>In the past I&#8217;ve also used the <a href="http://us2.php.net/manual/en/ini.core.php#ini.auto-prepend-file">auto_prepend_file</a> settings to run my script before anything (index.php) but I ran into some issues on different hosts, and it wasn&#8217;t as portable.</p>
<p>This is useful because you can have a file with globally available functions that you can use in non-WP areas as well as WP areas.  I am moving away from this more and more as I learn more about classes and build plugins instead for portability.</p>
<pre>
include_once ASKAPACHE_ROOT . &#039;/includes/myfunctions.inc&#039;;
&nbsp;
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . &#039;wp-settings.php&#039;);
?&gt;
</pre>
<h2>Some Useful PHP</h2>
<p>I am constantly trying to make my sites and code more portable, so I am using plugins alot more to accomplish things that I use to do with separate php.  Here are some examples of minimal php.</p>
<pre>
add_filter("the_generator", create_function(&#039;$a&#039;,&#039;return "";&#039;));
add_filter(&#039;the_content&#039;, create_function(&#039;$a&#039;, &#039;return ((is_feed())? $a."&lt;p&gt;&lt;a href=\"".get_permalink()."\"&gt;".get_the_title()."&lt;/a&gt; originally appeared on ".get_bloginfo("name").".&lt;/p&gt;" : $a);&#039;), 99999);
add_filter(&#039;excerpt_length&#039;, create_function(&#039;$a&#039;, &#039;return 300;&#039;),99);
add_filter(&#039;excerpt_more&#039;, create_function(&#039;$a&#039;, &#039;return "&hellip;";&#039;),99);
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"pingback\" href=\"&#039;.get_bloginfo(&#039;pingback_url&#039;).&#039;\" /&gt;\n";&#039;), 95 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"schema.rss\" href=\"http://purl.org/rss/1.0/\" /&gt;\n";&#039;), 96 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"schema.rel\" href=\"http://purl.org/vocab/relationship/\" /&gt;\n";&#039;), 97 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"meta\" type=\"application/rdf+xml\" href=\"/foaf.rdf\" /&gt;\n";&#039;), 98 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link href=\"/favicon.ico\" rel=\"shortcut icon\" type=\"image/x-icon\" /&gt;\n";&#039;), 99 );
</pre>
<h2>Debugging Note</h2>
<p><a href="http://wordpress.org/extend/plugins/askapache-debug-viewer/screenshots/"><img alt="AskApache Advanced Debugging Output" src="http://s.wordpress.org/extend/plugins/askapache-debug-viewer/screenshot-1.png?r=160129" title="AskApache Advanced Debugging Output" width="625" height="548" /></a>If you read this far than you probably know how important debugging is, but I sometimes like to stick the best tips deep in my articles to make sure only YOU find it.  GRTFM isn&#8217;t used on this site, it&#8217;s mostly a requirement because my writing can get pretty bad..  The point, debugging is more than a crucial requirement if you want to do anything cool.  Don&#8217;t worry I got you.. check my <a href="http://wordpress.org/extend/plugins/askapache-debug-viewer/">AskApache Debug Viewer Plugin from the official WP site</a>.  It&#8217;s pretty close to providing as verbose amount of information that I could possibly figure out how to get out of php, probably more than you have ever seen at least, I focused on quantity.  I use it all the time on new installs as there is no setup required and it tells me advanced information about the setup of the server, hacker code for sure.<br class="C" /></p>
<p>Here&#8217;s a quick function to see set global vars, I just think this is interesting code.</p>
<pre>
function askapache_global_debug(){
  global $_GET,$_POST,$_COOKIE,$_SESSION,$_ENV,$_FILES,$_SERVER,$_REQUEST,$HTTP_POST_FILES,$HTTP_POST_VARS,$HTTP_SERVER_VARS,$HTTP_RAW_POST_DATA,$HTTP_GET_VARS,$HTTP_COOKIE_VARS,$HTTP_ENV_VARS;
  $gv=create_function(&#039;$n&#039;,&#039;global $$n; ob_start(); if ( is_array($$n) &#038;&#038; sizeof($$n)&gt;0 &#038;&#038; print("[{$n}]\n") ) print_r($$n);return ob_get_clean();&#039;);
  foreach (array(&#039;_GET&#039;,&#039;_POST&#039;,&#039;_COOKIE&#039;,&#039;_SESSION&#039;,&#039;_ENV&#039;,&#039;_FILES&#039;,&#039;_SERVER&#039;,&#039;_REQUEST&#039;,&#039;HTTP_POST_FILES&#039;,&#039;HTTP_POST_VARS&#039;,&#039;HTTP_SERVER_VARS&#039;,&#039;HTTP_RAW_POST_DATA&#039;,&#039;HTTP_GET_VARS&#039;,&#039;HTTP_COOKIE_VARS&#039;,&#039;HTTP_ENV_VARS&#039;) as $k)echo $gv($k);
  print_r(get_defined_constants());
}
</pre>
<p class="anote">Also check the WordPress Codex page: <a href="http://codex.wordpress.org/Editing_wp-config.php">Editing wp-config.php</a></p>
<p><a href="http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html">Advanced WordPress wp-config.php Tweaks</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>mod_rewrite Fix for Caching Updated Files</title>
		<link>http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html</link>
		<comments>http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html#comments</comments>
		<pubDate>Sun, 30 Aug 2009 13:20:59 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[DreamHost]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Server Administration]]></category>
		<category><![CDATA[Web Design]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[Webmaster]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[Cache-Control]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[If-Modified-Since]]></category>

		<guid isPermaLink="false">http://www.askapache.com/htaccess/mod_rewrite-code-to-fix-caching-updated-files.html</guid>
		<description><![CDATA[<p>Web Developers sometimes use <code>file.ext?v=004</code> as a version control system to force visitors to use updated files.  <strong>This is terrible.</strong>  Instead link to <code>apache-003.css</code> and set it to be cached forever. When you change the file you just change the links to <code>apache-004.css</code>. That eliminates millions of bandwidth and resource robbing If-Modified-Since requests. You only need Apache with mod_rewrite, and 1-10 minutes!</p>]]></description>
			<content:encoded><![CDATA[<p><strong>Web Developers sometimes use</strong> <code>file.ext?v=137</code> as a <strong>version control system</strong> so they can force visitors to use an updated file.  <strong>This is so terrible</strong>.  Instead link to <code>apache-003.css</code> and set it to be cached forever. When you change the file you just change the links to <code>apache-004.css</code>.</p>
<h2>Raw Speed Benefit</h2>
<p>This eliminates millions of bandwidth and resource robbing <code>304 If-Modified-Since</code> requests.</p>
<hr />
<h2>Renaming links vs. Renaming files</h2>
<p>On the server my files are named <strong>apache.css</strong> and <strong>apache.js</strong>, but in the xhtml I point to them using the names <code>apache-113.css</code> and <code>apache-113.js</code>, after I change the file I just add 1 to the number, and the new file is cached. They are internally redirected to apache.css and apache.js (invisible to the user) The concept is similar to a &#8220;shortcut&#8221; in windows or a symlink in BSD.  The trick is that I never actually rename the files on the server.  I just rename them in the html.  That means <code>apache-135.css</code> is served from the file apache.css but the browser/cache only see and know about <code>apache-135.css</code>.</p>
<h2>XHTML</h2>
<p><strong>NOTE</strong>: You can do your own investigating of this sites source code and <a href="http://www.askapache.com/online-tools/http-headers-tool/">HTTP headers</a> to see this whole system in action</p>
<pre>
&lt;link href="http://z.askapache.com/z/c/apache-0031.css" rel="stylesheet" type="text/css" /&gt;
&lt;script src="http://z.askapache.com/z/j/apache-0031.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>
<h2>mod_rewrite code for htaccess or httpd.conf</h2>
<p><strong>Updated:</strong> 10/20/2008</p>
<pre>
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /z/([a-z]+)/(.+)-([0-9]+)\.(js|css).*\ HTTP/ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .+ /z/%2/%3.%5 [NC,L]
</pre>
<h3>Alternate mod_rewrite code</h3>
<pre>
RewriteEngine On
RewriteBase /
RewriteRule ^([cij]+)(/?[a-z]*)/([a-z]+)-([0-9]+)\.([a-z]+)$ /$1$2/$3.$5 [L]
</pre>
<h2>Ideal Caching Scheme</h2>
<p>Ok so you want the xhtml to be the only file that isn&#8217;t cached without being validated, its simple to <a href="http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html" title="Speed Up Sites with htaccess Caching">setup your own caching scheme</a>.</p>
<h3>Bad Cache information for a file with the <code>?v=foo</code> hack</h3>
<blockquote><p>This object will be fresh for 1 week. It can be validated with Last-Modified. This object requests that a Cookie be set; this makes it and other pages affected automatically stale; clients must check them upon every request. Because it contains a query (&#8216;?&#8217;) in the URL, many caches will not keep this object.</p>
</blockquote>
<p><a href="http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html">mod_rewrite Fix for Caching Updated Files</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom bash_profile for Advanced Shell Users</title>
		<link>http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html</link>
		<comments>http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html#comments</comments>
		<pubDate>Sun, 23 Aug 2009 18:32:26 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[.bashrc]]></category>
		<category><![CDATA[advanced]]></category>
		<category><![CDATA[alias]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[bash alias]]></category>
		<category><![CDATA[bash_profile]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[shell script]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=3183</guid>
		<description><![CDATA[<p class="anote">Want to get started with my custom bash file without reading this page <strong>(recommended as page is not updated)</strong>?  Execute the following in your shell and rock and roll.</p>
<pre>
curl -O http://z.askapache.com/askapache-bash-profile.txt &#038;& . askapache-bash-profile.txt
</pre>
]]></description>
			<content:encoded><![CDATA[<p>Looking for some advanced uses for the shell?  Function examples?  Advanced shell settings?  Here is some of my best.</p>
<p class="anote">Want to get started without even having to read this page?  Type the following in your shell.</p>
<pre>
curl -O http://z.askapache.com/askapache-bash-profile.txt &#038;&#038; source askapache-bash-profile.txt
</pre>
<p>For those of you power users and server admins that use Bash, ksh, csh, vanilla sh, etc.., or if you are just passionate about shell scripting, because it allows you to get advanced tasks done fast and efficiently, not to mention automated automatically.  I give you my .bash_profile file.   You should edit it to fit your needs, (especially the exported vars like PATH, LDFLAGS, if you don&#8217;t understand something just comment it out) but it&#8217;s pretty universal because I work on alot of other people&#8217;s servers not to mention many different distros and platforms, and when I get hired to do some server work through a shell, I bring this script along for the ride.</p>
<p><a href="/wp-content/uploads/2009/08/askapache-bash_profile.png"><img src="/wp-content/uploads/2009/08/askapache-bash_profile.png" alt="askapache-bash_profile" title="askapache-bash_profile" width="571" height="2879" /></a></p>
<h2>askapache-bash-profile.txt</h2>
<p>You can download the latest version: <a href="http://z.askapache.com/askapache-bash-profile.txt">http://z.askapache.com/askapache-bash-profile.txt</a></p>
<p>The functions and variables below are the way bash sees them, using declare -f, and alias, to make it easier for you to read and understand them.    The actual file at <a href="http://z.askapache.com/askapache-bash-profile.txt">http://z.askapache.com/askapache-bash-profile.txt</a> will always be the most updated version, as I use it personally.  And it has the whole file the way I wrote it, meaning many extra notes and much simpler to follow. Enjoy!</p>
<pre>
#!/bin/bash
#
# To install the latest version
#
# curl -O http://z.askapache.com/askapache-bash-profile.txt &#038;&#038; source askapache-bash-profile.txt
#
# To run automatically at login: In your ~/.bash_profile or similar login script do
# [[ -r path-to-askapache-bash-profile.txt ]] &#038;&#038; source path-to-askapache-bash-profile.txt
#
&nbsp;
AAPN=&#039;AskApache Bash Profile Script&#039;
AAPV=&#039;5.6&#039;
AAPT=&#039;2009-22-2009&#039;
AAPS=`echo "$0" | sed -e &#039;s,.*/,,&#039;`
&nbsp;
############################################################################################################################################################
# Copyright (C) 2009 www.AskApache.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;.
############################################################################################################################################################
&nbsp;
# dont do anything for non-interactive shells
[[ -z "$PS1"  ]] &#038;&#038; return
&nbsp;
# bash defines the following built-in commands:
#   :, ., [, alias, bg, bind, break, builtin, case, cd, command, compgen, complete, continue, declare, dirs
#   disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, if, jobs, kill,
#   let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend
#   test, times, trap, type, typeset, ulimit, umask, unalias, unset, until, wait, while
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# The first digit selects the set user ID (4) and set group ID (2) and sticky (1) attributes.
# The second digit selects permissions for the user who owns the file: read (4), write (2), and execute (1)
# The third selects permissions for other users in the file&#039;s group, with the same values
# The fourth for other users not in the file&#039;s group, with the same values.
# [see man chmod, help umask]
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
umask 0022
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# Trapping Signals to Catch Errors
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# 1      2      3       4      5       6       7      8      9       10      11      12      13      14      15      17      18      19      20      21
# SIGHUP SIGINT SIGQUIT SIGILL SIGTRAP SIGABRT SIGBUS SIGFPE SIGKILL SIGUSR1 SIGSEGV SIGUSR2 SIGPIPE SIGALRM SIGTERM SIGCHLD SIGCONT SIGSTOP SIGTSTP SIGTTIN
# [see man bash, man signal, help trap]
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
trap &#039;echo -e "\n\n\n!!! TERMINATED SIG: [$?] AT LINE:$LINENO AFTER $SECONDS SECONDS !!!\n"|tee -a `tty 2&gt;/dev/null`;&#039; 15
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# Advanced Shell Limits
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# -S      use the `soft&#039; resource limit
# -H      use the `hard&#039; resource limit
# -a      all current limits are reported
# -c      the maximum size of core files created
# -d      the maximum size of a process&#039;s data segment
# -f      the maximum size of files created by the shell
# -l      the maximum size a process may lock into memory
# -m      the maximum resident set size
# -n      the maximum number of open file descriptors
# -p      the pipe buffer size
# -s      the maximum stack size
# -t      the maximum amount of cpu time in seconds
# -u      the maximum number of user processes
# -v      the size of v
# [see man getrlimit, help ulimit]
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
ulimit -S -c 0 # Don&#039;t want any coredumps
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# Advanced Shell (set)tings
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# e [errexit] Exit immediately if a command exits with a non-zero status.
# B [braceexpand] The shell will perform brace expansion.
# h [hashall] Remember the location of commands as they
# f [noglob]      Disable file name generation (globbing).
# H [histexpand]  Enable ! style history substitution.
# v [verbose]     Print shell input lines as they are read.
# x [xtrace]      Print commands and their arguments as they are executed.
# n [noexec]      Read commands but do not execute them.
# [history] Enable command history
# [see man bash, help set]
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
set +C +f +H +v +x +n -b -h -i -m -B
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# Advanced Shell (shopt)ions
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# cdable_vars             an argument to the cd builtin command that is not a directory is assumed to be the name of a variable dir to change to.
# cdspell                 minor errors in the spelling of a directory component in a cd command will be corrected.
# checkhash               bash checks that a command found in the hash table exists before execute it.  If no longer exists, a path search is performed.
# checkwinsize            bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.
# cmdhist                 bash attempts to save all lines of a multiple-line command in the same history entry.  Allows re-editing of multi-line commands.
# dotglob                 bash includes filenames beginning with a `.&#039; in the results of pathname expansion.
# execfail                a non-int shell will not exit if it cannot execute the file specified as an argument to the exec builtin command, like int sh.
# expand_aliases          aliases are expanded as described above under ALIASES.  This option is enabled by default for interactive shells.
# extglob                 the extended pattern matching features described above under Pathname Expansion are enabled.
# histappend              the history list is appended to the file named by the value of the HISTFILE variable when shell exits, no overwriting the file.
# hostcomplete            and readline is being used, bash will attempt to perform hostname completion when a word containing a @ is being completed
# huponexit               bash will send SIGHUP to all jobs when an interactive login shell exits.
# interactive_comments    allow a word beginning with # to cause that word and all remaining characters on that line to be ignored in an interactive shell
# lithist                 if cmdhist option is enabled, multi-line commands are saved to the history with embedded newlines rather than using semicolon
# login_shell             shell sets this option if it is started as a login shell (see INVOCATION above).  The value may not be changed.
# mailwarn                file that bash is checking for mail has been accessed since the last checked, &#96;`The mail in mailfile has been read&#039;&#039; is displayed.
# no_empty_cmd_completion bash will not attempt to search the PATH for possible completions when completion is attempted on an empty line.
# nocaseglob              bash matches filenames in a case-insensitive fashion when performing pathname expansion (see Pathname Expansion above).
# nullglob                bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves.
# progcomp                the programmable completion facilities (see Programmable Completion above) are enabled.  This option is enabled by default.
# promptvars              prompt strings undergo variable and parameter expansion after being expanded as described in PROMPTING above.
# shift_verbose           the shift builtin prints an error message when the shift count exceeds the number of positional parameters.
# sourcepath              the source (.) builtin uses the value of PATH to find the directory containing the file supplied as an argument.
# xpg_echo                the echo builtin expands backslash-escape sequences by default.
# [see man bash, help shopt]
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
shopt -s histappend cmdhist extglob no_empty_cmd_completion checkwinsize progcomp sourcepath cdspell cdable_vars checkhash histreedit histverify
shopt -u mailwarn; unset MAILCHECK # dont notify for new mail
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;&#45;-
# CUSTOM SETTING VARIABLES
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;&#45;-
&nbsp;
# quicker, cleaner ref
export N6=/dev/null
&nbsp;
# if a program exists in path
function have()
{ unset -v have; PATH=$PATH:/sbin:/usr/sbin:/usr/local/sbin; type $1 &&gt;/$N6 &#038;&#038; have="yes"; }
&nbsp;
[[ -z ${USER:=""} ]] &#038;&#038; export USER=`whoami 2&gt;$N6 || id -un 2&gt;$N6 || logname 2&gt;$N6`
[[ -z ${HOME:=""} ]] &#038;&#038; export HOME=$(command pwd -L)
&nbsp;
export HOME=${HOME:-~};
export SHELL=${SHELL:-/bin/bash}
have tty &#038;&#038; export SSHTTY=`tty 2&gt;$N6`
&nbsp;
export TZ=&#039;America/Indianapolis&#039;
[[ -z "$HOST" ]] &#038;&#038; export HOST=`hostname 2&gt;$N6||uname -n 2&gt;$N6`
&nbsp;
# DEFINATELY EDIT THIS STUFF, is pretty good at setting path
#JAVA_HOME=/usr/local/jdk
#P=${PATH}:$HOME/bin:$HOME/sbin:/bin:/etc:/sbin:/usr/local/bin:/usr/sbin:/usr/X11R6/bin:/usr/bin:/usr/bin/mh:/usr/libexec:/etc/X11:/etc/X11/xinit:$HOME/.gem/ruby/1.8/bin
#P=${P}:/usr/local/dh/apache/template/bin:/usr/local/dh/apache2/template/bin:/usr/local/dh/apache2/template/build:/usr/local/dh/apache2/template/sbin
#P=${P}:/usr/local/dh/bin:/usr/local/dh/java/bin:/usr/local/dh/java/jre/bin:/usr/local/php5/bin:.
#PATH=$P
GP=; for p in ${PATH//:/ }; do [[ -d $p &#038;&#038; -x $p ]] &#038;&#038; [[ "${GP}s" == s ]] &#038;&#038; GP=$p || GP=${GP}:$p; done; export PATH=$GP
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;&#45;-
# LIBS / COMPILES - EDIT
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;&#45;-
#LDFLAGS="-L${HOME}/lib -L/lib -L/usr/lib -L/usr/lib/libc5-compat -L/lib/libc5-compat -L/usr/i486-linuxlibc1/lib -L/usr/X11R6/lib"; LD_LIBRARY_PATH=$HOME/lib; CPPFLAGS="-I${HOME}/include"
#export LDFLAGS LD_LIBRARY_PATH CPPFLAGS
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;&#45;-
# MAIL, PROGRAMS, EDITOR
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;&#45;-
have nano &#038;&#038; export EDITOR="`type -P nano`" &#038;&#038; export VISUAL=$EDITOR
have lynx &#038;&#038; export BROWSER="`type -P lynx`"
&nbsp;
#alias man=&#039;man -H&#039;
#[[ -r $HOME/.lynx/lynx.cfg ]] &#038;&#038; export LYNX_CFG=$HOME/.lynx/lynx.cfg
#[[ -r $HOME/var/locatedb ]] &#038;&#038; export LOCATE_PATH=$HOME/var/locatedb
&nbsp;
alias more=&#039;less&#039;
export PAGER=less
export LESSCHARSET=&#039;latin1&#039;
have lesspipe &#038;&#038; export LESSOPEN=&#039;|/usr/bin/lesspipe %s 2&gt;&#038;-&#039; &#038;&#038; export LESS=&#039;-i -N -w  -z-4 -g -e -M -X -F -R -P%t?f%f :stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-&#46;..&#039;
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# PROMPT
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# \a     an ASCII bell character (07)
# \d     the date in "Weekday Month Date" format (e.g., "Tue May 26")
# \D{format}  the format is passed to strftime(3) and the result is inserted into the prompt string;
# \e     an ASCII escape character (033)
# \h     the hostname up to the first `.&#039;
# \H     the hostname
# \j     the number of jobs currently managed by the shell
# \l     the basename of the shell&#039;s terminal device name
# \n     newline
# \r     carriage return
# \s     the name of the shell, the basename of $0 (the portion following the final slash)
# \t     the current time in 24-hour HH:MM:SS format
# \T     the current time in 12-hour HH:MM:SS format
# \@     the current time in 12-hour am/pm format
# \A     the current time in 24-hour HH:MM format
# \u     the username of the current user
# \v     the version of bash (e.g., 2.00)
# \V     the release of bash, version + patchelvel (e.g., 2.00.0)
# \w     the current working directory
# \W     the basename of the current working directory
# \!     the history number of this command
# \#     the command number of this command
# \$     if the effective UID is 0, a #, otherwise a $
# \nnn   the character corresponding to the octal number nnn
# \\     a backslash
# \[     begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
# \]     end a sequence of non-printing characters
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
&nbsp;
case ${TERM:-dummy} in linux*|con80*|con132*|console|xterm*|vt*|screen*|putty|Eterm|dtterm|ansi|rxvt|gnome*|*color*)COLORTERM=yes; ;; *) COLORTERM=no; ;; esac; export COLORTERM
PS1="\n[`date +%m/%d`][\u@\h][\w]($SHLVL:\!)\n$ "; X=;R=;
[[ "$COLORTERM" == yes ]] &#038;&#038; X=&#039;\033[1;37m&#039; &#038;&#038; R=&#039;\033[0;00m&#039; &#038;&#038; PS1="\n[`date +%m/%d`]\e[1;37m[\e[0;32m\u\e[0;35m@\e[0;32m\h\e[1;37m]\e[1;37m[\e[0;31m\w\e[1;37m]($SHLVL:\!)\n\[${X}\]\$ "
export PS1 R X
&nbsp;
# If set, the value is executed as a command prior to issuing each primary prompt.
have tty &#038;&#038; export SSHTTY=$(tty 2&gt;$N6);
[[ -z "$SSHTTY" ]] || export PROMPT_COMMAND=&#039;echo -ne "\033]0;$USER:`id -gn 2&gt;$N6`@$HOSTNAME `tty 2&gt;$N6`  [`uptime 2&gt;$N6|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `command ps aux|wc -l`]  `command w|wc -l` users \007"&#039;
unset PROMPT_COMMAND
&nbsp;
# used by functions below
export RJ=0;
declare -a CC;
export L1=$(seq -s_ 1 75|tr -d [0-9]);
export L2=$(echo $L1|tr &#039;_&#039; &#039; &#039;)
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# ls aliases
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
C=&#039; &#45;-color=auto&#039;
alias la="command ls -Al${C}"      # show hidden files
alias lx="command ls -lAXB${C}"    # sort by extension
alias lk="command ls -lASr${C}"    # sort by size
alias lc="command ls -lAcr${C}"    # sort by change time
alias lu="command ls -lAur${C}"    # sort by access time
alias lr="command ls -lAR${C}"     # recursive ls
alias lt="command ls -lAtr${C}"    # sort by date
alias lll="stat -c %a\ %N\ %G\ %U \$PWD/*|sort"
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# safety aliases
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
alias chmod=&#039;command chmod -c&#039;
alias mkdir=&#039;command mkdir -pv&#039;
alias rm=&#039;command rm -v&#039;
alias cp=&#039;command cp -v&#039;
alias mv=&#039;command mv -v&#039;
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# func aliases
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
alias who=&#039;command who -ar -pld&#039;
alias which=&#039;command type -path&#039;
have tree || alias tree=&#039;command -lsFR&#039;
have tree &#038;&#038; alias tree=&#039;command tree -Csuflapi&#039;
alias top=&#039;top -c&#039;
alias vim=&#039;command vim &#45;-noplugin&#039;
alias du=&#039;command du -kh&#039;
alias df=&#039;command df -kTh&#039;
[[ $UNAME != Linux ]] &#038;&#038; have gsed &#038;&#038; alias sed=gsed
#alias php=&#039;php -d display_errors=true&#039;
#alias man=&#039;man -H&#039;
#alias ldconfig="ldconfig -v -f ${HOME}/etc/ld.so.conf -C ${HOME}/etc/ld.so.cache"
alias path=&#039;echo -e ${PATH//:/\\n}&#039;
&nbsp;
alias pp=&#039;command ps -HAcl -F S -A f&#039;
alias p=&#039;command ps -HAcl -F S -A f|uniq -w3&#039;
alias ps2=&#039;command ps -H&#039;
alias ps1=&#039;command ps -lFA&#039;
&nbsp;
alias df1=&#039;command df -iTa&#039;
alias n="${EDITOR}"3
alias inice=&#039;ionice -c3 -n7 nice&#039;
alias vdir="ls &#45;-format=long"
alias dir="ls &#45;-format=vertical"
alias killphp=&#039;pkill -9 -f php.cgi\|php5.cgi\|php-cgi\|php\|php4.cgi;pkill -13 -f php.cgi\|php5.cgi\|php-cgi\|php\|php4.cgi&#039;
alias dsiz=&#039;du -sk * | sort -n &#45;-&#039;
alias lessc=&#039;ccze -A |/usr/bin/less -R&#039;
alias h=&#039;history&#039;
alias j=&#039;jobs -l&#039;
alias ..=&#039;cd ..&#039;
alias wtf=&#039;watch -n 1 w -hs&#039;
&nbsp;
# spelling typos
alias kk=&#039;ll&#039;
alias xs=&#039;cd&#039;
alias vf=&#039;cd&#039;
alias moer=&#039;more&#039;
alias moew=&#039;more&#039;
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# history setup
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# HISTCONTROL
#    If  set  to a value of ignorespace, lines which begin with a space character are not entered on the history list.
#    If set to a value of ignoredups, lines matching the last history line are not entered.  A value of ignoreboth combines the two options.
#    If unset, or if set to any other value than those above, all lines read by the parser are saved on the history list, subject to the value of HISTIGNORE.
# HISTFILE
#    The name of the file in which command history is saved (see HISTORY below).  The default value is ~/.bash_history.  If unset, the command history is not saved when an interactive shell exits.
# HISTFILESIZE
#    The  maximum number of lines contained in the history file.  When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines.
#    The default value is 500.  The history file is also trun-cated to this size after writing it when an interactive shell exits.
# HISTIGNORE
#    A colon-separated list of patterns used to decide which command lines should be saved on the history list.  Each pattern is anchored at the beginning of the line and must match the complete line (no implicit `*&#039; is appended).
#    Each pattern is  tested against  the  line  after  the  checks  specified  by HISTCONTROL are applied.  In addition to the normal shell pattern matching characters, `&#038;&#039; matches the previous history line.
#    `&#038;&#039; may be escaped using a backslash; the backslash is removed before attempting a match.  The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE.
# HISTSIZE
#    The number of commands to remember in the command history (see HISTORY below).  The default value is 500.
#
HISTMASTER=;HISTCONTROL=;HISTIGNORE=;HISTSIZE=;HISTFILESIZE=;HISTFILE=;HISTTIMEFORMAT=;
function asetup_history()
{
  HISTMASTER=${HISTMASTER:-$HOME/backups/.history/combined.log}
  HISTCONTROL=${HISTCONTROL:-&#039;ignoreboth&#039;}
  HISTTIMEFORMAT="%H:%M &gt; "
  HISTIGNORE=${HISTIGNORE:-&#039;clear:ll:ls:./_sbackup.sh:./_logview.sh:ps:updatedb:top&#039;}
  HISTSIZE=${HISTSIZE:-5000000}
  HISTFILESIZE=${HISTFILESIZE:-5000000}
  HISTFILE=${HISTFILE:-$HOME/.bash_history}
  export HISTMASTER HISTCONTROL HISTIGNORE HISTSIZE HISTFILESIZE HISTFILE HISTTIMEFORMAT
}
&nbsp;
function h1()
{ cat $HISTFILE $HISTMASTER | command grep $1 | sort | uniq | command grep &#45;-color=always $1; }
&nbsp;
function h2()
{ cat $HISTFILE $HISTMASTER | command grep $1 | sort | uniq; }
&nbsp;
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# personalized colors
#&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-&#45;&#45;-
# Attribute codes:        00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:       30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes: 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
# NORMAL 00       # global default, although everything should be something.
# FILE 00         # normal file
# DIR 01;34       # directory
# LINK 01;36      # symbolic link.
# FIFO 40;33      # pipe
# SOCK 01;35      # socket
# DOOR 01;35      # door
# BLK 40;33;01    # block device driver
# CHR 40;33;01    # character device driver
# ORPHAN 40;31;01 # symlink to nonexistent file
# EXEC 01;32      # executables
LS_COLORS=;LS_OPTIONS=;
function asetup_colors(){
 local L; eval "`dircolors -b`";
 [[ "$COLORTERM" == no ]] &#038;&#038; return
 export LS_COLORS
 unset LS_OPTIONS
}
&nbsp;
function ascript_title(){
  clear; echo; echo; lin 0;
  echo -e "| ${CC[2]}             ___       __    ___                 __                     ${CC[0]} |"
  echo -e "| ${CC[2]}            / _ | ___ / /__ / _ | ___  ___ _____/ /  ___                ${CC[0]} |"
  echo -e "| ${CC[9]}           / __ |(_-&lt;/  &#039;_// __ |/ _ \/ _ \`/ __/ _ \/ -_)               ${CC[0]} |"
  echo -e "| ${CC[9]}          /_/ |_/___/_/\_\/_/ |_/ .__/\_,_/\__/_//_/\__/                ${CC[0]} |"
  echo -e "| ${CC[9]}                               /_/                                      ${CC[0]} |";
  lin 1; lin 2 "${1:-$AAPN}"; lin 2 "Version ${2:-$AAPV}"; lin 2 "Build: ${3:-$AAPT}"; lin 3;sleep 2;
}
&nbsp;
###########################################################################&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-#
###
### FUNCTIONS
###
###########################################################################==-==-==-==-==-==-==-==-==-==-==#
&nbsp;
#export SMSO=$(tput smso &&gt;$N6);export RMSO=$(tput rmso &&gt;$N6);
#find . -type f -iname &#039;*htaccess*&#039; -print0 | xargs -0 grep -sn -i "THE_REQUEST" | sed "s/THE_REQUEST/${SMSO}\0$RMSO}/gI"
&nbsp;
function repeat()
{ local i max=$1; shift; for ((i=1; i &lt;= max ; i++)); do eval "$@"; done; }
&nbsp;
function cuttail()
{ sed -n -e :a -e "1,${2:-10}!{P;N;D;};N;ba" $1; }
&nbsp;
function quote()
{ echo \&#039;${1//\&#039;/\&#039;\\\&#039;\&#039;}\&#039;; }
&nbsp;
function dequote()
{ eval echo "$1"; }
&nbsp;
function get_pids_on_system()
{ command ps axo pid|sed 1d; }
&nbsp;
function get_pgids_on_system()
{ command ps axo pgid|sed 1d; }
&nbsp;
function get_users_on_system()
{ have getent &&gt;$N6 &#038;&#038; getent passwd|awk -F: &#039;{print $1}&#039; &#038;& return; awk &#039;BEGIN {FS=":"} {print $1}&#039; /etc/passwd; }
&nbsp;
function get_groups_on_system()
{ have getent &&gt;$N6 &#038;&#038; getent group|awk -F: &#039;{print $1}&#039; &#038;& return; awk &#039;BEGIN {FS=":"} {print $1}&#039; /etc/group; }
&nbsp;
function get_inet_interface_ips()
{ have ip &#038;&#038; /bin/ip -o -f inet addr|sed -e &#039;/inet 10./d&#039; -e &#039;s/\/24//g&#039; |awk &#039;{print $4}&#039;|sed -e "s/\\n//g" -e &#039;/.*\.0$/d&#039;; }
&nbsp;
function personalized_wget()
{
 exec 6&gt;&#038;1 ; exec &gt; ${1:-$HOME/.wgetrc}
 echo &#039;header = Accept-Language: en-us,en;q=0.5&#039;
 echo &#039;header = Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5&#039;
 echo &#039;header = Accept-Encoding: gzip,deflate&#039;
 echo &#039;header = Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7&#039;
 echo &#039;header = Keep-Alive: 300&#039;
 echo &#039;user_agent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6&#039;
 echo &#039;referer = http://www.google.com&#039;
 echo &#039;robots = off&#039;
 exec 1&gt;&#038;6 6&gt;&#038;-
}
&nbsp;
function mkdir()
{
 local e=0;
 for f in ${1+"$@"};do
 set fnord `echo ":$f"|sed -e &#039;s/^:\//%/&#039; -e &#039;s/^://&#039; -e &#039;s/\// /g&#039; -e &#039;s/^%/\//&#039;`;shift;pp=;for d in ${1+"$@"};do pp="$pp$d";
 case "$pp" in -*)pp=./$pp; ;; ?:)pp="$pp/";continue ;; esac; [[ ! -d "$pp" ]] &#038;&#038; mkdir -v "$pp"||e=$?; pp="$pp/"; done;
 done; return  $e
}
&nbsp;
function clean_exit()
{ lin 0;lin 1;lin 2 "COMPLETED SUCCESSFULLY";lin 1;lin 3; }
&nbsp;
function dirty_exit()
{ echo "See ya..";sleep 1;exit; }
&nbsp;
function set_window_title()
{ echo -n -e "\033]0;$*\007"; }
&nbsp;
function pd()
{ echo -e  "\n ${CC[15]} ${1:-DONE} $R\n\n" &gt;$SSHTTY; }
&nbsp;
function cont()
{ local ans; echo -en "\n ${CC[15]}[ ${1:-Press any key to continue} ]$R\n"; read -n 1 ans; }
&nbsp;
function do_sleep ()
{ echo -en "${CC[6]}${3:-.}" &gt;$SSHTTY;while [[ -d /proc/$RJ ]];do sleep ${2:-3};echo -en "${3:-.}" &gt;$SSHTTY;done;echo -e "${CC[0]}" &gt;$SSHTTY&#038;&#038;sleep 1&&pd; }
&nbsp;
function pwd()
{ command pwd -LP "$@"; }
&nbsp;
function kill_jobs(){
 for i in `jobs -p`; do kill -9 $i; done; }
&nbsp;
function beep_alarm()
{ local i; for i in `seq 0 ${1:-5}`;do echo -en "\a" &#038;&#038; sleep 1; done; }
&nbsp;
function lin()
{ case ${1:-1} in 0)echo -e "\n$R $L1"; ;; 1)echo -e "|$L2|"; ;; 2)echo -en "${R}|${CC[34]}";echo -en "${2:-1}"|sed -e :a -e &#039;s/^.\{1,72\}$/ &#038; /;ta&#039; -e "s/\(.*\)/\1/";echo -e "${R} |${R}" ;; 3)echo -e "$R $L1$R$X\n\n"; ;; esac; }
&nbsp;
function mp3info()
{ ls *.mp3 |xargs -ix 2&gt;&#038;1 ffmpeg -i x|grep -v "^Must" |grep -v "built\|libavutil\|libavcodec\|configuration\|FFmpeg\|libavformat"; }
&nbsp;
function tailit()
{ clear;echo "p e a ma md all | FILENAME"; sh ${HOME}/scripts/logview.sh "${2:-askapache.com}" "${1:-all}"; }
&nbsp;
function pm()
{ local S I=${1:-3};S=$SSHTTY;echo -en "$R\n";case ${2:-0} in 0)echo -en "${CC[6]}==&gt; $X$I$R" &gt;$S; ;; 3)echo -e "\n\n${CC[4]}:: $X$I$R\n" &gt;$S; ;; esac; }
&nbsp;
function yes_no()
{ local a YN=65; echo -en "${1:-Answer} [y/n] "; read -n 1 a; case $a in [yY]) YN=0; ;; esac; return $YN; }
&nbsp;
function l()
{ command ls -AhFp &#45;-color=auto "$@"; }
&nbsp;
function la()
{ du *|awk &#039;{print $2,$1}&#039;|sort -n|tr &#039; &#039; "\t"; }
&nbsp;
function ll()
{ command ls -lABls1c &#45;-color=auto "$@"; }
&nbsp;
function stat1()
{ local D=${1:-$PWD/*}; stat -c %a\ %A\ \ A\ %x\ \ M\ %y\ \ C\ %z\ \ %N ${D} |sed -e &#039;s/ [0-9:]\{8\}\.[0-9]\{9\} -[0-9]\+//g&#039; |tr  -d "\`\&#039;"|sort -r; }
&nbsp;
function stat2()
{ local D=${1:-$PWD/*}; stat -c %a\ %A\ \ A\ %x\ \ M\ %y\ \ C\ %z\ \ %N ${D} |sed -e &#039;s/\.[0-9]\{9\} -[0-9]\+//g&#039;|tr  -d "\`\&#039;"|sort -r; }
&nbsp;
#&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-=&#45;-#
# processes
#==-==-==-==-==-==-==-==-==-==-==#
function psu()
{ command ps -Hcl -F S f -u ${1:-$USER}; }
&nbsp;
function ps()
{ [[ -z "$1" ]] &#038;&#038; command ps -Hacl -F S -A f &#038;& return; command ps "$@"; }
&nbsp;
function make_nice()
{ have nice || return; pm "Making Nice $$"; pm 0 0; command renice ${1:-19} -p $$; pd; }
&nbsp;
function make_ionice()
{ have ionice || return; pm "Making IONice $$"; pm 0 0; command ionice -c${1:-3} -n7 -p $$; pd; }
&nbsp;
function dump_ps_environment()
{ command ps aux | grep ${USER:0:3} | awk &#039;{print $2}&#039; | xargs -t -ipid cat /proc/pid/environ; }
&nbsp;
function procinfo1()
{ PI=($(strace -s1 procinfo -a 2&gt;&#038;1|sed -e &#039;/^op/!d&#039; -e &#039;/pro/!d&#039; -e &#039;/= -1/d&#039;|sed -e &#039;s%o.*"/proc/\(.*\)".*% \1%g&#039;)); for i in ${PI[*]}; do echo -e "\n&#45;&#45;-===[  /proc/$i  ]\n" &#038;&#038; cat /proc/$i &#038;&#038; echo -e "\n\n"; done; }
&nbsp;
function pss(){
  local U PPS PL PX PXX UUS=( $(command ps uax|awk &#039;{print $1}&#039;|command tail -n +2|sort|uniq) ); UL=$((${#UUS[@]} - 1))
  exec 6&gt;&#038;1; exec &gt; ~/proc.$$
  ps aux | grep ${USER:0:3} | awk &#039;{print $2}&#039; | xargs -t -ipid cat /proc/pid/environ
  for UX in $(seq 0 1 $UUS); do U=${UUS[$UX]}; PPS=( $(pgrep -u ${U}) ); PL=$((${#PPS[@]} - 1));
   for PX in $(seq 0 1 $PL); do PXX=${PPS[$PX]};echo -e "\n\n\n&#45;&#45;&#45;-- PROCESS ID: ${PXX} &#45;&#45;&#45;--\n\n";cat /proc/${PXX}/cmdline 2&gt;$N6 || echo;echo -e "\n\n"; command tree -Csuflapi /proc/Q/${PXX};done
  done
  exec 1&gt;&#038;6 6&gt;&#038;-; cat ~/proc.$$ | more
}
&nbsp;
function ashow_motd()
{ [[ -r /etc/motd ]] &#038;&#038; echo -e "\n\n${CC[2]}`head -n 7 /etc/motd | tail -n 6`${R}\n"; }
&nbsp;
function ashow_calendar()
{ [[ -d /usr/share/calendar/ ]] &#038;&#038; echo -en "\n${CC[5]}" &#038;&#038; ( sed = $(echo /usr/share/calendar/calendar*) | sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" ) &#038;&#038; echo -en "${R}"; }
&nbsp;
function ashow_fortune()
{ [[ -x /usr/games/fortune ]] &#038;&#038; echo -en "\n${CC[6]}" &#038;&#038; /usr/games/fortune -s &#038;&#038; echo -en "${R}"; }
&nbsp;
function askapache()
{
  ascript_title
  ashow_motd
&nbsp;
  have who &#038;&#038; pm "Users" &#038;&#038; pm "Logged In" 3 &#038;&#038;  command who -ar -pld
  pm "Current Limits" 3;command ulimit -a
&nbsp;
  pm "Machine stats";
  have uptime &#038;&#038; pm "uptime" 3 &#038;&#038; command uptime
  [[ -d /proc ]] &#038;&#038; [[ -f /proc/meminfo ]] &#038;&#038; cat /proc/meminfo
  have who &#038;&#038; pm "Users" 3 &#038;&#038; command who
&nbsp;
  pm "Networking"
  have ip &#038;&#038; pm "interfaces" 3 &#038;&#038; ip -o addr|sed -e &#039;s/ \{1,\}/\t/g&#039;
  [[ -r /proc/net/sockstat ]] &#038;&#038; pm "Sockets" 3 &#038;&#038; head -n 2 /proc/net/sockstat
  have ss &#038;&#038; pm "Networking Stats" 3 &#038;&#038; ss -s
  have netstat &#038;&#038; pm "Routing Information" 3 &#038;&#038; netstat -r
&nbsp;
  pm "Disk"
  pm "Mounts" 3; command df -hai
  #[[ -d /sys/block/ ]] &#038;&#038; pm "IO Scheduling" 3; for d in /sys/block/[a-z][a-z][a-z]*/queue/*; do [[ -d $d ]] &#038;&#038; tree $d; echo "$d =&gt; $(cat $d)";done
  have iostat &#038;&#038; pm "I/O on Disks" &#038;&#038; iostat -p ALL
&nbsp;
  pm "Processes";
  pm "process tree" 3;  command ps -HAcl -F S -A f | uniq -w3
  have procinfo &#038;&#038; pm "procinfo" 3 &#038;&#038; procinfo|head -n 13|tail -n 11
}
&nbsp;
asetup_colors
asetup_history
askapache
&nbsp;
</pre>
<p><a href="http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html">Custom bash_profile for Advanced Shell Users</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>An AskApache Plugin Upgrade to Rule them All</title>
		<link>http://www.askapache.com/wordpress/an-askapache-plugin-upgrade-to-rule-them-all.html</link>
		<comments>http://www.askapache.com/wordpress/an-askapache-plugin-upgrade-to-rule-them-all.html#comments</comments>
		<pubDate>Wed, 29 Jul 2009 17:59:07 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Apache Modules]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[Web Tools]]></category>
		<category><![CDATA[Webmaster]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress Plugins]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[AskApache Google 404]]></category>
		<category><![CDATA[AskApache Password Protection]]></category>
		<category><![CDATA[Fsockopen]]></category>
		<category><![CDATA[wordpress security]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=3062</guid>
		<description><![CDATA[<p><a class="IFL" href="/wp-content/uploads/2009/07/apache-server-status.png"><img src="/wp-content/uploads/2009/07/apache-server-status-350x164.png" alt="apache-server-status" title="apache-server-status" width="350" height="164" class="alignnone size-medium wp-image-3070" /></a>So my blog as been rather quiet for almost a year now, and very few updates if any have been released for my Password Protection PLugin, my Google 404 Plugin, and definately not for my AskApache CrazyCache plugin, which I will be releasing last...  So for all of you who've helped me out by sending me suggestions and notifying me of errors and sticking with it...  Just wanted to <strong>say sorry about that, and thanks for all the great ideas.. </strong> Well, I've been sticking with it as well believe it our not.  I manage to get free days once in a while, and then its <strong>time to jam</strong>.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a class="IFL" href="/wp-content/uploads/2009/07/apache-server-status.png"><img src="/wp-content/uploads/2009/07/apache-server-status-350x164.png" alt="apache-server-status" title="apache-server-status" width="350" height="164" class="alignnone size-medium wp-image-3070" /></a>So my blog as been rather quiet for almost a year now, and very few updates if any have been released for my Password Protection PLugin, my Google 404 Plugin, and definately not for my AskApache CrazyCache plugin, which I will be releasing last&#8230;  So for all of you who&#8217;ve helped me out by sending me suggestions and notifying me of errors and sticking with it&#8230;  Just wanted to <strong>say sorry about that, and thanks for all the great ideas.. </strong> Well, I&#8217;ve been sticking with it as well believe it our not.  I manage to get free days once in a while, and then its <strong>time to jam</strong>.</p>
<p>I&#8217;ve used just about every CMS/Blog/Forum/Trac/Gallery/etc) and really didn&#8217;t like a lot of the way they coded&#8230;  I could use php but I didn&#8217;t KNOW php.. so I&#8217;ve had to learn php also, and it was tough to learn the advanced class usage and all the other language specific (but similar) constructs for php.  It was especially difficult (but fun and challenging) to program so as to be compatible with php4 and php5 (Such is WordPress).    But I kept at it, and soon you can decide for yourself what to make of it.</p>
<p>I can code in plenty of languages (bash, lua, windows .bat and vbs,  ocaml, big fan of all things shell) and can work my way through C and even sorta somewhat with assembly.  Assembly is the hardest, by far,  I&#8217;m into easy and powerful languages like Python, Javascript, perl, php, ruby, and CGI. I&#8217;ve used PHP for a long time to do various things,  but never to build software projects like this.  Once I noticed WordPress&#8217;s core .php files and the excellent programming I wanted to try and learn hot to do it.   The WordPress code is some of the best I&#8217;ve seen.  It appears the way they built it was planned, and not just dreamt up while typing that I can&#8217;t help but do.    Every time I read through the core code I learn a new trick or very nice way to do something.  Those guys are really good, and I think WordPress is going to dominate for a long long time.</p>
<h2>The Strategy</h2>
<p>The Password Protection (passpro) plugin has a lot of complex stuff going on, especially for a newbie to PHP and WordPress like me, so after refactoring the whole thing at least 5 times I decided to modify my approach, and wrote the AskApache Google 404 Plugin as a way to practice on a simpler piece of code, while at the same time providing a plugin of value.   Eventually I stopped thinking I could just code the whole thing in one sit-down with a stream-of-consciousness, and had to instead modularize the code and focus in on each part before moving to the next (I go without a plan because its fun, just not the most productive, but again, I&#8217;m not a programmer in the scientific sense.).</p>
<p>So I decided I had to really learn how WordPress Plugins work, filters, hooks, actions, and basically comfortability at reverse-engineering code, (Im a beginner for the last time), and so with the upcoming release of the AskApache Google 404 Plugin I have succeeded in making an incredibly stable plugin.  That way I only have to worry about what the aapasspro plugin is doing, instead of trying to fit it into a framework.  </p>
<h2>AskApache Google 404 Upgrade</h2>
<p>I think its rather unusual to develop a nice plugin like this 404 handler merely for the purpose of improving upon another plugin, but hey it worked.  As of <em>08/03/2009 14:06PM EST</em> I have about 1 hour left of finishing touches to release this upgrade.  But as you cantell by my badly edited posts, I don&#8217;t have a lot of time to myself.  An hour here and there is about it.  So it could be up to 2 weeks before I actually have the time to commit the release to the repo.  On a sidenote, have you checked out <a href="http://windows7news.com/" title="Windows 7 News">Windows 7 News</a>?  I&#8217;ve been contracted to do some technical work for them and thought they had an excellent site.</p>
<p><a href="/wp-content/uploads/2009/07/askapache-google-upgrade-ss1.png"><img src="/wp-content/uploads/2009/07/askapache-google-upgrade-ss1-344x350.png" alt="askapache-google-upgrade-ss1" title="askapache-google-upgrade-ss1" width="344" height="350" class="alignnone size-medium wp-image-3139" /></a></p>
<p><a href="/wp-content/uploads/2009/07/askapache-google-upgrade-ss2.png"><img src="/wp-content/uploads/2009/07/askapache-google-upgrade-ss2-293x350.png" alt="askapache-google-upgrade-ss2" title="askapache-google-upgrade-ss2" width="293" height="350" class="alignnone size-medium wp-image-3138" /></a></p>
<p>But keep in mind, the 404 PLugin is just where I practice for the passpro plugin, which truly does have features that no other software like it has ever had.  I understand the technology behind this plugin, and know it would really have a great impact on improving the Web (esp. WordPress) for all of us, I&#8217;ve just had to learn how to make it.</p>
<h2>AskApache Password Protection</h2>
<p>Probably still a couple weeks away, this plugin is the ultimate culmination of apache hackers dreams, at least those on shared servers (who may be interested in learning how to bypass security of said servers)..  So this is something I have much too fun with doing what I like to do.. network/protocol-level security.  I&#8217;ve examined the source code for many software packages that I use or have used to audit a server&#8217;s security, and this simple php plugin in most instances can enumerate with accuraccy most of the server&#8217;s setup in about a minute.  The catch (and the file permission problems I had to find a workaround too) is that this software is launched on the server, not remotely against the server.</p>
<p>Some of the software I examined was whiskers, nessus, nmap, hping, mozilla source, wireshark, ncftp, netcat, etc..  The closest comparison to the socket-level class I&#8217;ve hacked together to those is wireshark.  Except that wireshark only interprets (captures) the data passing over the wire, while this class does that and in fact sends and receives the data like netcat or nmap.  Its really more similar to metasploit, and can easily be used to send hex, binary, ascii, or any type of payload to the remote or local host.</p>
<h2>The Upgrades Begin</h2>
<p>Well I started working on them a long time ago.  Both the Password Protection plugin and the Google 404 plugin needed serious work.   And I finally have it all figured out.  Essentially I would work on one and finish an upgrade, but I just wasn&#8217;t happy with it and I wold start all over again, refactoring the code.   So as I put the finishing touches on those 2 plugins keep an eye out.  They are major upgrades.   I was able to meet all the goals I had for them, and came up with a lot of more improvements during the process.One of the main things I needed was a socket-level class to perform all kinds of checks and tests on.  I need this also for my crazy cache plugin, which my blog is currently using ,  and I have a 2 more really nice pplugins I use that also needed  access to a network class.  I wrote about what I was doing with fsockopen, and I&#8217;ve been improving on that example ever since.  I use this class to do some really powerful and exciting stuff, but you&#8217;ll see it soon enough.  As an indication of &#8216;getting it right&#8217; for the Password Protection plugin, the plugin will now work on Windows, Apache, IIS, Lighthttpd, and will even work running on a blackberry web server.  So now everyone using wordpress can at least get some security()</p>
<p class="enote">Many of the the other improvements focus on using the fsockopen class and .htaccess tricks to basically enumerate and discover all the different capabilities of your particular server;  That way you can learn about all the features and security that are possible for your specific server, and the securty modules wi8ll be geared for that as well.  FINALLY this plugin is going to be stable, and I just cant wait to see how people react when they learn all great capability their Apache-based Server has that they didn&#8217;t have a clue about.   Its amazing in that sense, and hackers will love theh way it works.. but your server admins will love it even more because its entirely 100% focused on helping you to set your site up (if you have Apache) to keep spammers out, to keep virii-serving robots and their log-hogging exploit requests and CPU/Mem robiing 404 errors off of your servers for real.  This will have a noticeable affect to whoever is running the server.   As you can tell.. I am pumped!</br></p>
<hr class="C" />
Apache is easy to configure and use, but only when you have root access.  Most people on shared and private hosting aren&#8217;t even able to view the main config file, let alone execute the Apache binaries to see what features are available and what configuration is being used.<br class="C" /></p>
<p>Apache can only be influenced by the main server configs and by .htaccess files.  Not by php, not by perl, and the main configs are almost never accessible to the masses.  But .htaccess files are.  And many hosting providers allow and enable .htaccess files, a configuration file for your web server.  The advanced features and capabilities of Apache were out of reach for most of us, it just wasn&#8217;t possible to enumerate or access, and most hosting providers are infamous for their lack of .htaccess (customer) support.  This plugin goes around those problems to give the power back to the people.<br class="C" /></p>
<p>y creating custom .htaccess files containing unpublished .htaccess tricks and techniques and combining that with the use of socket-level networking from WordPress (PHP) using <a href="http://www.askapache.com/php/fsockopen-socket.html">fsockopen</a>, we can effectively enumerate and discover an incredible amount of features and settings you will be able to control and use with this plugin.</p>
<p>Here are a few examples of the capabilities of this plugin, some of which I believe no other software can do..  <em>(Open source free to copy!)</em>.</p>
<ol>
<li>Current Version of Apache (<strong>Down to the API Version</strong>)</li>
<li>List of <strong>ALL Modules currently enabled</strong> by Apache (Such as Mod_Rewrite)</li>
<li>List of <strong>ALL Directives enabled by EACH enabled Module.</strong></li>
<li>Enumerate .htaccess Overrides, Context Permissions</li>
<li>Test for any builtin Handlers (like the <a href="/wp-content/uploads/2009/07/apache-server-status.png">status handler screenshot</a>)</li>
<li>Configure SSI (<a href="http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-security">http://www.askapache.com/htaccess/advanced-htaccess-ssi.html#htaccess-ssi-security</a>)</li>
</ol>
<blockquote cite="http://www.askapache.com/htaccess/password-protection-plugin-status.html"><div class="inote"><cite><a href="http://www.askapache.com/htaccess/password-protection-plugin-status.html"></a></cite>
<p><strong>March 1, 2009</strong><br /><strong>I would focus on the method that WordPress uses</strong>.  The code they have now (2.8 bleeding-edge) still isn&#8217;t where it needs to be, but this is some difficult stuff and <strong>they have a brilliant start, it&#8217;ll work.. just a question of when</strong>.</p>
<p><a class="IFL" href="/wp-content/uploads/2009/03/apache-security-model-tall1.png"><img src="/wp-content/uploads/2009/03/apache-security-model-tall1-250x123.png" alt="Apache Security Model - In Color" title="apache-security-model-wide" width="250" height="123" /></a><strong>The main issue</strong> with the password protection plugin working for some people and not others is due to <a title="detailed file permission article" href="http://www.askapache.com/security/chmod-stat.html">file permission configurations</a>.  The plugin attempts to write/modify files in your blog&#8217;s root directory.<br class="C" /></p>
</div>
</blockquote>
<hr class="C" />
<blockquote cite="http://www.askapache.com/htaccess/htaccess-plugin-blocks-spam-hackers-and-password-protects-blog.html"><div class="inote"><cite><a href="http://www.askapache.com/htaccess/htaccess-plugin-blocks-spam-hackers-and-password-protects-blog.html"></a></cite>
<p><strong>November 05, 2008</strong><br />To make a long story short, I downloaded each major release of the apache httpd source code starting at version 1.3.0 and finishing with version 2.2.11, I then compiled each version and built a HTTPD from source for all these apache versions.</p>
<div>
<div style="width:100px;overflow:hidden;float:left;">
<ul>
<li>1.3.0</li>
<li>1.3.1</li>
<li>1.3.11</li>
<li>1.3.12</li>
<li>1.3.14</li>
<li>1.3.17</li>
<li>1.3.19</li>
<li>1.3.2</li>
<li>1.3.20</li>
<li>1.3.22</li>
<li>1.3.23</li>
<li>1.3.24</li>
<li>1.3.27</li>
<li>1.3.28</li>
</ul>
</div>
<div style="width:100px;overflow:hidden;float:left;">
<ul>
<li>1.3.29</li>
<li>1.3.3</li>
<li>1.3.31</li>
<li>1.3.32</li>
<li>1.3.33</li>
<li>1.3.34</li>
<li>1.3.35</li>
<li>1.3.36</li>
<li>1.3.37</li>
<li>1.3.39</li>
<li>1.3.4</li>
<li>1.3.41</li>
<li>1.3.6</li>
<li>1.3.9</li>
</ul>
</div>
<div style="width:100px;overflow:hidden;float:left;">
<ul>
<li>2.0.35</li>
<li>2.0.36</li>
<li>2.0.39</li>
<li>2.0.40</li>
<li>2.0.42</li>
<li>2.0.43</li>
<li>2.0.44</li>
<li>2.0.45</li>
<li>2.0.46</li>
<li>2.0.47</li>
<li>2.0.48</li>
<li>2.0.49</li>
<li>2.0.50</li>
<li>2.0.51</li>
</ul>
</div>
<div style="width:150px;overflow:hidden;float:left;">
<ul>
<li>2.0.52</li>
<li>2.0.53</li>
<li>2.0.54</li>
<li>2.0.55</li>
<li>2.0.58</li>
<li>2.0.59</li>
<li>2.0.61</li>
<li>2.0.63</li>
<li>2.1.3-beta</li>
<li>2.1.6-alpha</li>
<li>2.1.7-beta</li>
<li>2.1.8-beta</li>
<li>2.1.9-beta</li>
</ul>
</div>
<div style="width:100px;overflow:hidden;float:left;">
<ul>
<li>2.2.0</li>
<li>2.2.10</li>
<li>2.2.2</li>
<li>2.2.3</li>
<li>2.2.4</li>
<li>2.2.6</li>
<li>2.2.8</li>
<li>2.2.9</li>
<li><strong>2.2.10</strong></li>
<li><strong>2.2.11</strong></li>
</ul>
</div>
<p><br class="C" /></div>
<p>Then I went through each version and determined the compatible modules for that version, and I&#8217;m pretty confident that I was also able to find each and every directive allowed by the compatible modules for that version (including core directives).  See <a href="http://www.askapache.com/htaccess/htaccess.html#htaccess-directives">.htaccess directive list</a>.  Basically I can now test a server using a variety of methods and determine almost 100% accurately what version of Apache (down to the API) is running, what modules (and versions) are enabled, and each and every directive that is allowed or disallowed for that version.  So this is so awesome because now we can enable all sorts of additional security features.</p>
</div>
</blockquote>
<hr class="C" />
<blockquote cite="http://www.askapache.com/htaccess/htaccess.html#htaccess-modules"><p><cite><a href="http://www.askapache.com/htaccess/htaccess.html#htaccess-modules">Htaccess enabled Modules</a></cite>
<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="http://www.askapache.com/servers/mod_actions.c.html">mod_actions</a>, <a href="http://www.askapache.com/servers/mod_alias.c.html">mod_alias</a>, <a href="http://www.askapache.com/servers/mod_asis.c.html">mod_asis</a>, <a href="http://www.askapache.com/servers/mod_auth_basic.c.html">mod_auth_basic</a>, <a href="http://www.askapache.com/servers/mod_auth_digest.c.html">mod_auth_digest</a>, <a href="http://www.askapache.com/servers/mod_authn_anon.c.html">mod_authn_anon</a>, <a href="http://www.askapache.com/servers/mod_authn_dbd.c.html">mod_authn_dbd</a>, <a href="http://www.askapache.com/servers/mod_authn_dbm.c.html">mod_authn_dbm</a>, <a href="http://www.askapache.com/servers/mod_authn_default.c.html">mod_authn_default</a>, <a href="http://www.askapache.com/servers/mod_authn_file.c.html">mod_authn_file</a>, <a href="http://www.askapache.com/servers/mod_authz_dbm.c.html">mod_authz_dbm</a>, <a href="http://www.askapache.com/servers/mod_authz_default.c.html">mod_authz_default</a>, <a href="http://www.askapache.com/servers/mod_authz_groupfile.c.html">mod_authz_groupfile</a>, <a href="http://www.askapache.com/servers/mod_authz_host.c.html">mod_authz_host</a>, <a href="http://www.askapache.com/servers/mod_authz_owner.c.html">mod_authz_owner</a>, <a href="http://www.askapache.com/servers/mod_authz_user.c.html">mod_authz_user</a>, <a href="http://www.askapache.com/servers/mod_autoindex.c.html">mod_autoindex</a>, <a href="http://www.askapache.com/servers/mod_cache.c.html">mod_cache</a>, <a href="http://www.askapache.com/servers/mod_cern_meta.c.html">mod_cern_meta</a>, <a href="http://www.askapache.com/servers/mod_cgi.c.html">mod_cgi</a>, <a href="http://www.askapache.com/servers/mod_dav.c.html">mod_dav</a>, <a href="http://www.askapache.com/servers/mod_dav_fs.c.html">mod_dav_fs</a>, <a href="http://www.askapache.com/servers/mod_dbd.c.html">mod_dbd</a>, <a href="http://www.askapache.com/servers/mod_deflate.c.html">mod_deflate</a>, <a href="http://www.askapache.com/servers/mod_dir.c.html">mod_dir</a>, <a href="http://www.askapache.com/servers/mod_disk_cache.c.html">mod_disk_cache</a>, <a href="http://www.askapache.com/servers/mod_dumpio.c.html">mod_dumpio</a>, <a href="http://www.askapache.com/servers/mod_env.c.html">mod_env</a>, <a href="http://www.askapache.com/servers/mod_expires.c.html">mod_expires</a>, <a href="http://www.askapache.com/servers/mod_ext_filter.c.html">mod_ext_filter</a>, <a href="http://www.askapache.com/servers/mod_file_cache.c.html">mod_file_cache</a>, <a href="http://www.askapache.com/servers/mod_filter.c.html">mod_filter</a>, <a href="http://www.askapache.com/servers/mod_headers.c.html">mod_headers</a>, <a href="http://www.askapache.com/servers/mod_ident.c.html">mod_ident</a>, <a href="http://www.askapache.com/servers/mod_imagemap.c.html">mod_imagemap</a>, <a href="http://www.askapache.com/servers/mod_include.c.html">mod_include</a>, <a href="http://www.askapache.com/servers/mod_info.c.html">mod_info</a>, <a href="http://www.askapache.com/servers/mod_log_config.c.html">mod_log_config</a>, <a href="http://www.askapache.com/servers/mod_log_forensic.c.html">mod_log_forensic</a>, <a href="http://www.askapache.com/servers/mod_logio.c.html">mod_logio</a>, <a href="http://www.askapache.com/servers/mod_mem_cache.c.html">mod_mem_cache</a>, <a href="http://www.askapache.com/servers/mod_mime.c.html">mod_mime</a>, <a href="http://www.askapache.com/servers/mod_mime_magic.c.html">mod_mime_magic</a>, <a href="http://www.askapache.com/servers/mod_negotiation.c.html">mod_negotiation</a>, <a href="http://www.askapache.com/servers/mod_proxy.c.html">mod_proxy</a>, <a href="http://www.askapache.com/servers/mod_proxy_ajp.c.html">mod_proxy_ajp</a>, <a href="http://www.askapache.com/servers/mod_proxy_balancer.c.html">mod_proxy_balancer</a>, <a href="http://www.askapache.com/servers/mod_proxy_connect.c.html">mod_proxy_connect</a>, <a href="http://www.askapache.com/servers/mod_proxy_ftp.c.html">mod_proxy_ftp</a>, <a href="http://www.askapache.com/servers/mod_proxy_http.c.html">mod_proxy_http</a>, <a href="http://www.askapache.com/servers/mod_rewrite.c.html">mod_rewrite</a>, <a href="http://www.askapache.com/servers/mod_setenvif.c.html">mod_setenvif</a>, <a href="http://www.askapache.com/servers/mod_speling.c.html">mod_speling</a>, <a href="http://www.askapache.com/servers/mod_ssl.c.html">mod_ssl</a>, <a href="http://www.askapache.com/servers/mod_status.c.html">mod_status</a>, <a href="http://www.askapache.com/servers/mod_substitute.c.html">mod_substitute</a>, <a href="http://www.askapache.com/servers/mod_unique_id.c.html">mod_unique_id</a>, <a href="http://www.askapache.com/servers/mod_userdir.c.html">mod_userdir</a>, <a href="http://www.askapache.com/servers/mod_usertrack.c.html">mod_usertrack</a>, <a href="http://www.askapache.com/servers/mod_version.c.html">mod_version</a>, <a href="http://www.askapache.com/servers/mod_vhost_alias.c.html">mod_vhost_alias</a></p>
</blockquote>
<hr class="C" />
<hr class="C" />
<h2>Debugging HTTP protocol</h2>
<p>Check this out!  I&#8217;m particularly happy about this feature, which outputs an exact trace of any requests made by the plugin (such as during the testing phase) by saving the actual raw data sent out on the wire using fsockopen, RX and TX.  This is useful for a number of reasons, viewing your headers, finding Redirect Loops, testing RewriteRules, and following the request hop-by-hop for debugging.  The below example shows 2 requests for 2 URIs.  The first URI is protected using Digest Authentication, the 2nd shows Basic.</p>
<pre>
 ______________
|  RAW TRACE   |
==================================================================================================================================
GET /htaccess/index.txt?testing=query HTTP/1.1
Host: www.askapache.com
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1) AA_PassPro/1.9 (http://www.askapache.com/)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://www.askapache.com/
&nbsp;
HTTP/1.1 401 Authorization Required
Date: Wed, 22 Jul 2009 06:29:58 GMT
Server: Apache
WWW-Authenticate: Digest realm="do or die", nonce="03328f3ec7c7b", algorithm=MD5, domain="/", qop="auth"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 882
Connection: close
Content-Type: text/html; charset=UTF-8
&nbsp;
GET /htaccess/index.txt?testing=query HTTP/1.1
Host: www.askapache.com
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1) AA_PassPro/1.9 (http://www.askapache.com/)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://www.askapache.com/
Authorization: Digest username="test",realm="do or die",nonce="03328f3ec7c7b",uri="/htaccess/index.txt?testing=query",
cnonce="82d057852a9dc497",nc=00000001,algorithm=MD5,response="9d476e9ea3",qop="auth"
&nbsp;
HTTP/1.1 200 OK
Date: Wed, 22 Jul 2009 06:29:58 GMT
Server: Apache
Authentication-Info: rspauth="9051b01ee26dd62b3e2b40dada694f45", cnonce="82d057852a9dc497", nc=00000001, qop=auth
Last-Modified: Tue, 21 Jul 2009 23:56:00 GMT
Accept-Ranges: bytes
Cache-Control: max-age=3600
Expires: Wed, 22 Jul 2009 07:29:58 GMT
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 27
Connection: close
Content-Type: text/plain; charset=UTF-8
&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;``
&nbsp;
 ______________
|  RAW TRACE   |
==================================================================================================================================
GET /htaccess/po.txt?testing=query HTTP/1.1
Host: www.askapache.com
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1) AA_PassPro/1.9 (http://www.askapache.com/)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://www.askapache.com/
&nbsp;
HTTP/1.1 401 Authorization Required
Date: Wed, 22 Jul 2009 06:29:58 GMT
Server: Apache
WWW-Authenticate: Basic realm="Po Pimping"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 878
Connection: close
Content-Type: text/html; charset=UTF-8
&nbsp;
GET /htaccess/po.txt?testing=query HTTP/1.1
Host: www.askapache.com
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1) AA_PassPro/1.9 (http://www.askapache.com/)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://www.askapache.com/
Authorization: Basic adfAGAltcA==
&nbsp;
HTTP/1.1 200 OK
Date: Wed, 22 Jul 2009 06:29:58 GMT
Server: Apache
Last-Modified: Wed, 22 Jul 2009 05:54:39 GMT
Accept-Ranges: bytes
Cache-Control: max-age=3600
Expires: Wed, 22 Jul 2009 07:29:58 GMT
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 27
Connection: close
Content-Type: text/plain; charset=UTF-8
&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;`&#96;``
</pre>
<h2>.htaccess Directives</h2>
<p>AcceptFilter, AcceptMutex, AcceptPathInfo, AccessFileName, Action, AddAlt, AddAltByEncoding, AddAltByType, AddCharset, AddDefaultCharset, AddDescription, AddEncoding, AddHandler, AddIcon, AddIconByEncoding, AddIconByType, AddInputFilter, AddLanguage, AddModuleInfo, AddOutputFilter, AddOutputFilterByType, AddType, Alias, AliasMatch, AllowCONNECT, AllowEncodedSlashes, AllowOverride, Anonymous, Anonymous_Authoritative, Anonymous_LogEmail, Anonymous_MustGiveEmail, Anonymous_NoUserID, Anonymous_NoUserId, Anonymous_VerifyEmail, AssignUserId, AuthAuthoritative, AuthBasicAuthoritative, AuthBasicProvider, AuthDBDUserPWQuery, AuthDBDUserRealmQuery, AuthDBM, AuthDBMAuthoritative, AuthDBMGroupFile, AuthDBMType, AuthDBMUserFile, AuthDefaultAuthoritative, AuthDigestAlgorithm, AuthDigestDomain, AuthDigestFile, AuthDigestGroupFile, AuthDigestNcCheck, AuthDigestNonceFormat, AuthDigestNonceLifetime, AuthDigestProvider, AuthDigestQop, AuthDigestShmemSize, AuthGroupFile, AuthLDAPAuthzEnabled, AuthLDAPBindDN, AuthLDAPBindON, AuthLDAPBindPassword, AuthLDAPCharsetConfig, AuthLDAPCompareDNOnServer, AuthLDAPDereferenceAliases, AuthLDAPEnabled, AuthLDAPFrontPageHack, AuthLDAPGroupAttribute, AuthLDAPGroupAttributeIsDN, AuthLDAPRemoteUserAttribute, AuthLDAPRemoteUserIsDN, AuthLDAPStartTLS, AuthLDAPURL, AuthLDAPUrl, AuthName, AuthType, AuthUserFile, AuthzDBMAuthoritative, AuthzDBMType, AuthzDefaultAuthoritative, AuthzGroupFileAuthoritative, AuthzLDAPAuthoritative, AuthzOwnerAuthoritative, AuthzUserAuthoritative, BS2000Account, BalancerMember, BrowserMatch, BrowserMatchNoCase, BufferedLogs, CGIMapExtension, CacheDefaultExpire, CacheDirLength, CacheDirLevels, CacheDisable, CacheEnable, CacheExpiryCheck, CacheFile, CacheForceCompletion, CacheGcClean, CacheGcDaily, CacheGcInterval, CacheGcMemUsage, CacheGcUnused, CacheIgnoreCacheControl, CacheIgnoreHeaders, CacheIgnoreNoLastMod, CacheLastModifiedFactor, CacheMaxExpire, CacheMaxFileSize, CacheMaxStreamingBuffer, CacheMinFileSize, CacheNegotiatedDocs, CacheRoot, CacheSize, CacheStoreNoStore, CacheStorePrivate, CacheTimeMargin, CharsetDefault, CharsetOptions, CharsetSourceEnc, CheckCaseOnly, CheckSpelling, ChildPerUserId, ContentDigest, CookieDomain, CookieExpires, CookieLog, CookieName, CookieStyle, CookieTracking, CoreDumpDirectory, CustomLog, DAV, DAVDepthInfinity, DAVGenericLockDB, DAVMinTimeout, DBDExptime, DBDKeep, DBDMax, DBDMin, DBDParams, DBDPersist, DBDPrepareSQL, DBDriver, Dav, DavDepthInfinity, DavGenericLockDB, DavLockDB, DavMinTimeout, DefaultIcon, DefaultLanguage, DefaultType, DeflateBufferSize, DeflateCompressionLevel, DeflateFilterNote, DeflateMemLevel, DeflateWindowSize, Directory, DirectoryIndex, DirectoryMatch, DirectorySlash, DocumentRoot, DumpIOInput, DumpIOOutput, EnableExceptionHook, EnableMMAP, EnableSendfile, ErrorDocument, ErrorLog, Example, ExpiresActive, ExpiresByType, ExpiresDefault, ExtFilterDefine, ExtFilterOptions, ExtendedStatus, FancyIndexing, FileETag, Files, FilesMatch, FilterChain, FilterDeclare, FilterProtocol, FilterProvider, FilterTrace, ForceLanguagePriority, ForceType, ForensicLog, GprofDir, GracefulShutdownTimeout, Group, Header, HeaderName, HostNameLookups, HostnameLookups, ISAIPFakeAsync, ISAPIAppendLogToErrors, ISAPIAppendLogToQuery, ISAPICacheFile, ISAPIFakeAsync, ISAPILogNotSupported, ISAPIReadAheadBuffer, IdentityCheck, IdentityCheckTimeout, IfDefine, IfModule, IfVersion, ImapBase, ImapDefault, ImapMenu, Include, IndexIgnore, IndexOptions, IndexOrderDefault, IndexStyleSheet, KeepAlive, KeepAliveTimeout, LDAPCacheEntries, LDAPCacheTTL, LDAPCertDBPath, LDAPConnectionTimeout, LDAPOpCacheEntries, LDAPOpCacheTTL, LDAPSharedCacheFile, LDAPSharedCacheSize, LDAPTrustedClientCert, LDAPTrustedGlobalCert, LDAPTrustedMode, LDAPVerifyServerCert, LanguagePriority, Limit, LimitExcept, LimitInternalRecursion, LimitRequestBody, LimitRequestFields, LimitRequestFieldsize, LimitRequestLine, LimitXMLRequestBody, Listen, ListenBacklog, LoadFile, LoadModule, Location, LocationMatch, LockFile, LogFormat, LogLevel, MCacheMaxObjectCount, MCacheMaxObjectSize, MCacheMaxStreamingBuffer, MCacheMinObjectSize, MCacheRemovalAlgorithm, MCacheSize, MMapFile, MaxClients, MaxKeepAliveRequests, MaxMemFree, MaxRequestsPerChild, MaxSpareServers, MaxSpareThreads, MaxSpareThreadsPerChild, MaxThreads, MetaDir, MetaFiles, MetaSuffix, MimeMagicFile, MinSpareServers, MinSpareThreads, ModMimeUsePathInfo, MultiviewsMatch, NWSSLTrustedCerts, NWSSLUpgradeable, NameVirtualHost, NoProxy, NumServers, Options, PassEnv, PerlAccessHandler, PerlAuthenHandler, PerlAuthzHandler, PerlChildExitHandler, PerlChildInitHandler, PerlCleanupHandler, PerlDispatchHandler, PerlFixupHandler, PerlFreshRestart, PerlHandler, PerlHeaderParserHandler, PerlInitHandler, PerlLogHandler, PerlModule, PerlPassEnv, PerlPostReadRequestHandler, PerlRequire, PerlRestartHandler, PerlSendHeader, PerlSetEnv, PerlSetVar, PerlSetupEnv, PerlTaintCheck, PerlTransHandler, PerlTypeHandler, PerlWarn, PidFile, Port, Protocol, ProtocolEcho, Proxy, ProxyBadHeader, ProxyBlock, ProxyDomain, ProxyErrorOverride, ProxyFtpDirCharset, ProxyIOBufferSize, ProxyMatch, ProxyMaxForwards, ProxyPass, ProxyPassInterpolateEnv, ProxyPassMatch, ProxyPassReverse, ProxyPassReverseCookieDomain, ProxyPassReverseCookiePath, ProxyPreserveHost, ProxyReceiveBufferSize, ProxyRemote, ProxyRemoteMatch, ProxyRequests, ProxySet, ProxyStatus, ProxyTimeout, ProxyVia, RLimitCPU, RLimitMEM, RLimitNPROC, ReadmeName, Redirect, RedirectMatch, RedirectPermanent, RedirectTemp, RemoveCharset, RemoveEncoding, RemoveHandler, RemoveInputFilter, RemoveLanguage, RemoveOutputFilter, RemoveType, RequestHeader, Require, RewriteBase, RewriteCond, RewriteEngine, RewriteLock, RewriteLog, RewriteLogLevel, RewriteMap, RewriteOptions, RewriteRule, SSIAccessEnable, SSIEndTag, SSIErrorMsg, SSIStartTag, SSITimeFormat, SSIUndefinedEcho, SSLCACertificateFile, SSLCACertificatePath, SSLCADNRequestFile, SSLCADNRequestPath, SSLCARevocationFile, SSLCARevocationPath, SSLCertificateChainFile, SSLCertificateFile, SSLCertificateKeyFile, SSLCipherSuite, SSLCryptoDevice, SSLEngine, SSLHonorCipherOrder, SSLLog, SSLLogLevel, SSLMutex, SSLOptions, SSLPassPhraseDialog, SSLProtocol, SSLProxyCACertificateFile, SSLProxyCACertificatePath, SSLProxyCARevocationFile, SSLProxyCARevocationPath, SSLProxyCipherSuite, SSLProxyEngine, SSLProxyMachineCertificateFile, SSLProxyMachineCertificatePath, SSLProxyProtocol, SSLProxyVerify, SSLProxyVerifyDepth, SSLRandomSeed, SSLRequire, SSLRequireSSL, SSLSessionCache, SSLSessionCacheTimeout, SSLUserName, SSLVerifyClient, SSLVerifyDepth, Satisfy, ScoreBoardFile, Script, ScriptAlias, ScriptAliasMatch, ScriptInterpreterSource, ScriptLog, ScriptLogBuffer, ScriptLogLength, ScriptStock, SecureListen, SendBufferSize, ServerAdmin, ServerAlias, ServerLimit, ServerName, ServerPath, ServerRoot, ServerSignature, ServerTokens, SetEnv, SetEnvIf, SetEnvIfNoCase, SetHandler, SetInputFilter, SetOutputFilter, StartServers, StartThreads, Substitute, SuexecUserGroup, ThreadLimit, ThreadStackSize, ThreadsPerChild, TimeOut, Timeout, TraceEnable, TransferLog, TypeAuthDBMUserFile, TypesConfig, UnsetEnv, UseCanonicalName, UseCanonicalPhysicalPort, User, UserDir, VirtualDocumentRoot, VirtualDocumentRootIP, VirtualHost, VirtualScriptAlias, VirtualScriptAliasIP, Win32DisableAcceptEx, XBitHack, allow, deny, order, php_admin_flag, php_admin_value, php_flag, php_value</p>
<p class="anote">You can view the <a href="http://www.askapache.com/htaccess/htaccess-security-block-spam-hackers.html">plugins home page</a>, <a href="http://www.askapache.com/wordpress/htaccess-password-protect.html#aadl">old</a>, or <a href="http://wordpress.org/extend/plugins/askapache-password-protect/">view it on the wordpress.org site</a>.</p>
<p><a href="http://www.askapache.com/wordpress/an-askapache-plugin-upgrade-to-rule-them-all.html">An AskApache Plugin Upgrade to Rule them All</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/wordpress/an-askapache-plugin-upgrade-to-rule-them-all.html/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP and AJAX shell console</title>
		<link>http://www.askapache.com/ajax/php-and-ajax-shell-console.html</link>
		<comments>http://www.askapache.com/ajax/php-and-ajax-shell-console.html#comments</comments>
		<pubDate>Sun, 14 Jun 2009 01:01:15 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[DreamHost]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Server Administration]]></category>
		<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[Web Tools]]></category>
		<category><![CDATA[Webmaster]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[console]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[Shell]]></category>
		<category><![CDATA[shell console]]></category>

		<guid isPermaLink="false">http://www.askapache.com/tools/php-and-ajax-shell-console.html</guid>
		<description><![CDATA[<p><a class="IFL" href='http://www.askapache.com/tools/php-and-ajax-shell-console.html' title='PHP AJAX shell console'><img src='/wp-content/uploads/2007/08/php-ajax-shell-console.thumbnail.png' alt='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>Ever wanted to execute commands on your server through php to mimick a shell login? <strong>Now you can.</strong>  I&#8217;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&#45;-;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&#8217;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/ajax/php-and-ajax-shell-console.html">PHP and AJAX shell console</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/ajax/php-and-ajax-shell-console.html/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>DNS Round Robin Configuration using Rsync over SSH</title>
		<link>http://www.askapache.com/linux-unix/dns-round-robin-rsync-over-ssh.html</link>
		<comments>http://www.askapache.com/linux-unix/dns-round-robin-rsync-over-ssh.html#comments</comments>
		<pubDate>Tue, 14 Apr 2009 05:46:20 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Apache Modules]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[DNS]]></category>
		<category><![CDATA[DreamHost]]></category>
		<category><![CDATA[HostGator]]></category>
		<category><![CDATA[Powweb]]></category>
		<category><![CDATA[Round Robin]]></category>
		<category><![CDATA[rsync]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=2540</guid>
		<description><![CDATA[<p><a class="IFL" href="http://www.askapache.com/dreamhost/dns-round-robin-rsync-over-ssh.html"><img src="/wp-content/uploads/2009/04/round-robin-dns-116x98.png" /></a><strong>The goal is to add the HostGator server</strong> to be an exact mirror of the z.askapache.com domain, then to add that server as a 2nd A record to my DNS zone.  That way half the visitors to the size will be taking up resources and bandwidth on the <a href="http://secure.hostgator.com/cgi-bin/affiliates/clickthru.cgi?id=AskApache-rrdns">HostGator</a> server instead of mine.<br /><br /><strong>Round Robin A records</strong> in DNS are intended to evenly distribute queries between each host of the same name.  Using some tricks straight out of a hackers toolbox we can verify if the distribution is taking place.  (<a href="http://www.askapache.com/dreamhost/dns-round-robin-rsync-over-ssh.html#dns-robin-works">It is.</a>)  <br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p>My traffic is growing, alot, and I need to plan how I&#8217;m going to maintain scalability, high availability, and redundancy.   Scalability is an application&#8217;s ability to support a growing number of users. High availability can be defined as redundancy or speed.  I decided to setup <a href="#dns-robin-round">Round Robin DNS</a> for <a href="http://z.askapache.com/">z.askapache.com</a>, which is the &#8220;static&#8221; <a href="http://www.askapache.com/htaccess/apache-speed-subdomains.html">subdomain</a> of <a href="http://www.askapache.com/">AskApache</a> that serves all the static assets like images, javascript, css, etc.. (<em>BTW, the z stands for ZAP</em>)..  All I needed to attempt setting this up was another hosting account on a separate server.  I have hosting accounts with around 10 different companies from working with various clients over the years, like <a href="http://www.powweb.com/join/index.bml?AffID=582654">Powweb</a> and I don&#8217;t use them because they suck in terms of the unix environment.  Many of these web hosts are actually very fast bandwidth-wise..</p>
<h2><a id="#round-robin-concept" name="#round-robin-concept"></a>Round Robin Concept</h2>
<p><a class="IFL" href="#"><img src="/wp-content/uploads/2009/04/round-robin-dns.png" alt="Round Robin DNS" title="Round Robin DNS" width="396" height="335" class="size-full wp-image-2622" /></a><strong>A few months ago</strong> I was given a free hosting account on <a href="http://secure.hostgator.com/cgi-bin/affiliates/clickthru.cgi?id=AskApache-rrdns">HostGator</a> to evaluate and tempt me away from DreamHost to become a Gator.  I get a lot of these types of offers from time to time from the smaller Web companies who read AskApache.. but when I noticed the SSH access was jailed and saw how restrictive the shell was I felt like I was on a windows box..  I want a shell, cpanel sucks.  I compile and run everything from the shell so thats was a deal-breaker and I sorta forgot all about it.</p>
<p><strong>The goal is to add the HostGator server</strong> to be an <a href="http://www.askapache.com/security/mirror-using-rsync-ssh.html">exact mirror</a> of the z.askapache.com domain, then to add that server as a 2nd A record to my DNS zone.  That way half the visitors to the size will be taking up resources and bandwidth on the <a href="http://secure.hostgator.com/cgi-bin/affiliates/clickthru.cgi?id=AskApache-rrdns">HostGator</a> server instead of mine.</p>
<p><strong>Round Robin A records</strong> in DNS are intended to evenly distribute queries between each host of the same name.  Using some tricks straight out of a <a href="http://www.askapache.com/security/computer-security-toolbox-2.html">hackers toolbox</a> we can <a href="#dns-robin-works">verify if the distribution</a> is taking place.  (<a href="#dns-robin-works">It is.</a>)  <br class="C" /></p>
<h2><a id="#dns-robin-dns" name="#dns-robin-dns"></a>DNS &#8211; Domain Name System</h2>
<p>The Domain Name System is often analogized as a &#8220;phone book&#8221; for the Internet because it translates human-friendly computer hostnames into IP addresses. For example, <code>www.askapache.com</code> translates to <code>208.113.134.190</code>.  Every request for a human-friendly hostname first needs to be translated to the IP before the server can be queried.  Normally each hostname corresponds to exactly 1 IP address.  But in a Round Robin setup, the idea is to have the hostname correspond to multiple IP addresses, which are different servers that house the exact same content, resulting in some hosts requesting files from one server, and another host requesting files from the other server, resulting in less CPU resources and bandwidth.</p>
<p>Here is an the zone for <code>z.askapache.com</code> Round Robin records:</p>
<table summary="Round Robin DNS Records" id="ver-zebra">
<colgroup>
<col class="e" />
<col class="o" />
<col class="e" />
<col class="o" />
<col class="e" /></colgroup>
<thead>
<tr>
<th scope="col" class="e">QUERY</th>
<th scope="col" class="o">TTL</th>
<th scope="col" class="e">CLASS</th>
<th scope="col" class="o">TYPE</th>
<th scope="col" class="e">ANSWER</th>
</tr>
</thead>
<tbody>
<tr>
<td>z.askapache.com</td>
<td>13084</td>
<td>IN</td>
<td>A</td>
<td>64.111.114.111</td>
</tr>
<tr>
<td>z.askapache.com</td>
<td>13084</td>
<td>IN</td>
<td>A</td>
<td>69.56.174.114</td>
</tr>
</tbody>
</table>
<h2><a id="#dns-robin-round" name="#dns-robin-round"></a>Round Robin DNS</h2>
<p>Round robin DNS is a technique of load distribution, load balancing, or fault-tolerance provisioning multiple, redundant Internet Protocol service hosts, e.g., Web servers, FTP servers, by managing the Domain Name System&#8217;s (DNS) responses to address requests from client computers according to an appropriate statistical model.</p>
<p>In its simplest implementation Round-robin DNS works by responding to DNS requests not only with a single IP address, but a list of IP addresses of several servers that host identical services. The order in which IP addresses from the list are returned is the basis for the term round robin. With each DNS response, the IP address sequence in the list is permuted. Usually, basic IP clients attempt connections with the first address returned from a DNS query so that on different connection attempts clients would receive service from different providers, thus distributing the overall load among servers.</p>
<p>Round robin DNS is often used for balancing the load of geographically-distributed Web servers. For example, a company has one domain name and three identical web sites residing on three servers with three different IP addresses. When one user accesses the home page it will be sent to the first IP address. The second user who accesses the home page will be sent to the next IP address, and the third user will be sent to the third IP address. In each case, once the IP address is given out, it goes to the end of the list. The fourth user, therefore, will be sent to the first IP address, and so forth.</p>
<p>Although easy to implement, round robin DNS has problematic drawbacks, such as those arising from record caching in the DNS hierarchy itself, as well as client-side address caching and reuse, the combination of which can be difficult to manage. Round robin DNS should not solely be relied upon for service availability. If a service at one of the addresses in the list fails, the DNS will continue to hand out that address and clients will still attempt to reach the inoperable service.</p>
<h2><a id="#dns-robin-works" name="#dns-robin-works" title="Efficacy of DNS Load Balancing"></a>Does Round Robin Work</h2>
<p>Definately.  I can look at the access logs for both servers and see that they are splitting the requests nicely.   It is definately not an exact split however, look at these statistics and you&#8217;ll see what I mean.</p>
<pre class='brushbash'>
$ dig @ns1.dreamhost.com +authority +all z.askapache.com
&nbsp;
;; ANSWER SECTION:
z.askapache.com.        14400   IN      A       69.56.174.114
z.askapache.com.        14400   IN      A       64.111.114.111
&nbsp;
$ dig @ns1.dreamhost.com +authority +all z.askapache.com
&nbsp;
;; ANSWER SECTION:
z.askapache.com.        14400   IN      A       64.111.114.111
z.askapache.com.        14400   IN      A       69.56.174.114
</pre>
<p>The effects of caching will distort the effectiveness of any IP address allocation algorithm unless a 0 TTL is used which has the effect of significantly increasing the load on the DNS (and is not always implemented consistently). In this case the cure may be worse than the disease Good news we have good load balancing on our web servers. Bad news we need 17 more DNS servers!. Intuitively, and without running any experiments to verify, we would suggest that given a normal TTL (12 hours or more) and ANY IP allocation algorithm other than a single static list, loads should be reasonably balanced .</p>
<p><strong>Full root server query</strong></p>
<pre class='brushbash'>
Tracing to z.askapache.com[a] via A.ROOT-SERVERS.NET, maximum of 3 retries
A.ROOT-SERVERS.NET [.] (198.41.0.4)
 |\___ L.GTLD-SERVERS.NET [com] (192.41.162.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ D.GTLD-SERVERS.NET [com] (192.31.80.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ J.GTLD-SERVERS.NET [com] (192.48.79.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ H.GTLD-SERVERS.NET [com] (192.54.112.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ E.GTLD-SERVERS.NET [com] (192.12.94.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ F.GTLD-SERVERS.NET [com] (192.35.51.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ I.GTLD-SERVERS.NET [com] (192.43.172.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ G.GTLD-SERVERS.NET [com] (192.42.93.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ B.GTLD-SERVERS.NET [com] (2001:0503:231d:0000:0000:0000:0002:0030) Not queried
 |\___ B.GTLD-SERVERS.NET [com] (192.33.14.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ A.GTLD-SERVERS.NET [com] (2001:0503:a83e:0000:0000:0000:0002:0030) Not queried
 |\___ A.GTLD-SERVERS.NET [com] (192.5.6.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ C.GTLD-SERVERS.NET [com] (192.26.92.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ M.GTLD-SERVERS.NET [com] (192.55.83.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
  \___ K.GTLD-SERVERS.NET [com] (192.52.178.30)
       |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
       |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
        \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
&nbsp;
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       z.askapache.com -&gt; 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       z.askapache.com -&gt; 69.56.174.114
</pre>
<h2><a id="#dns-online-tools" name="#dns-online-tools"></a>Live Online DNS Tools</h2>
<ul>
<li><a href="http://member.dnsstuff.com/amember/go.php?r=323972&#038;i=l0">DNSstuff.com &#8211; Your Destination for DNS and Networking Tools</a></li>
<li><a href="http://www.zonecheck.fr/cgi-bin/zc.cgi?zone=askapache.com&#038;ns0=ns1.dreamhost.com&#038;ips0=&#038;ns1=ns2.dreamhost.com&#038;ips1=&#038;ns2=ns3.dreamhost.com&#038;ips2=&#038;ns3=&#038;ips3=&#038;ns4=&#038;ips4=&#038;ns5=&#038;ips5=&#038;ns6=&#038;ips6=&#038;ns7=&#038;ips7=&#038;intro=t&#038;explain=t&#038;details=t&#038;progress=counter&#038;report=byseverity&#038;format=html&#038;lang=en&#038;errorlvl=allwarning&#038;profile=automatic&#038;chkmail=t&#038;chkzone=t&#038;chkrir=t&#038;transp3=ipv4&#038;transp3=ipv6&#038;transp4=std">ZoneCheck</a></li>
<li><a href="http://pingability.com/zoneinfo.jsp?domain=askapache.com">Quick Check &#8211; Pingability.com</a></li>
<li><a href="http://www.squish.net/dnscheck/dnscheck.cgi?host=askapache.com&#038;type=ANY&#038;show_rootservers=on&#038;removebroken=on&#038;cnameprocessing=on&#038;show_mainworkings=on&#038;show_resolving=on&#038;show_allservers=on&#038;getbindversions=on&#038;retries=5&#038;querylevel=15">Squishywishywoo: complete dns traversal checking</a></li>
<li><a href="http://www.zonecut.net/dns/?domain=askapache.com&#038;find_subs=on">ZoneCut DNS</a></li>
<li><a href="http://atrey.karlin.mff.cuni.cz/~mj/sleuth/?domain=askapache.com&#038;verbose=ON&#038;server=ns1.dreamhost.com&#038;serverip=&#038;action=Submit&#038;.cgifields=verbose">DNS Sleuth</a></li>
<li><a href="http://www.pweb.cz/en/dns-test/dom.php">DNS test &#8211; Domain name DNS test &#8211; pweb.cz</a></li>
<li><a href="http://www.opendns.com/support/cache/?d=z.askapache.com">OpenDNS &#8211; Support &#8211; CacheCheck</a></li>
<li><a href="http://www.dnscolos.com/dnsreport.php">DNSReport</a></li>
<li><a href="http://freedns.afraid.org/domain/dnstrace.php?domain=askapache.com&#038;submit=Trace">DNSTrace</a></li>
<li><a href="http://www.intodns.com/askapache.com">intoDNS</a></li>
<li><a href="http://www.dnsthru.com/">DNSthru.com</a></li>
<li><a href="http://demo.dnsdoctor.org/cgi-bin/diagnose.cgi?zone=askapache.com&#038;ns0=ns1.dreamhost.com&#038;ips0=&#038;ns1=ns2.dreamhost.com&#038;ips1=&#038;ns2=ns3.dreamhost.com&#038;ips2=&#038;ns3=&#038;ips3=&#038;ns4=&#038;ips4=67.19.1.10&#038;ns5=&#038;ips5=67.19.0.10&#038;ns6=&#038;ips6=67.18.150.114&#038;ns7=&#038;ips7=&#038;intro=t&#038;format=html&#038;lang=en&#038;testname=t&#038;explain=t&#038;details=t&#038;progress=testdesc&#038;errorlvl=allwarning&#038;dontstop=nostop&#038;profile=automatic&#038;report=byseverity&#038;chkmail=t&#038;transp3=ipv4&#038;transp3=ipv6&#038;transp4=std">DNS Doctor</a></li>
<li><a href="http://www.checkdns.net/powercheck.aspx">Power Check</a></li>
</ul>
<h2><a id="#dns-links" name="#dns-links"></a>More Reading</h2>
<ul>
<li><a href="http://www.zytrax.com/books/dns/ch9/rr.html">HOWTO &#8211; Configure Load Balancing</a></li>
<li><a href="http://ntrg.cs.tcd.ie/undergrad/4ba2.01/group8/DNS.html">Load Sharing with DNS</a></li>
</ul>
<h3><a id="#dns-rfc-list" name="#dns-rfc-list"></a>RFC&#8217;s related to DNS</h3>
<ul>
<li><a href="http://rfc.askapache.com/rfc920/rfc920.html" title="protocol,signature,resource,dnssec,records,response,record,dnskey,algorithm,standards,domain,server,resolver,security">RFC 920</a>:  Specified original TLDs: .arpa, .com, .edu, .org, .gov, .mil and two-character country codes</li>
<li><a href="http://rfc.askapache.com/rfc1032/rfc1032.html">RFC 1032</a>:  Domain administrators guide</li>
<li><a href="http://rfc.askapache.com/rfc1033/rfc1033.html">RFC 1033</a>:  Domain administrators operations guide</li>
<li><a href="http://rfc.askapache.com/rfc1034/rfc1034.html">RFC 1034</a>:  Domain Names &#8211; Concepts and Facilities.</li>
<li><a href="http://rfc.askapache.com/rfc1035/rfc1035.html">RFC 1035</a>:  Domain Names &#8211; Implementation and Specification</li>
<li><a href="http://rfc.askapache.com/rfc1101/rfc1101.html">RFC 1101</a>:  DNS Encodings of Network Names and Other Types</li>
<li><a href="http://rfc.askapache.com/rfc1123/rfc1123.html">RFC 1123</a>:  Requirements for Internet Hosts &#8212; Application and Support</li>
<li><a href="http://rfc.askapache.com/rfc1912/rfc1912.html">RFC 1912</a>:  Common DNS Operational and Configuration Errors</li>
<li><a href="http://rfc.askapache.com/rfc1995/rfc1995.html">RFC 1995</a>:  Incremental Zone Transfer in DNS</li>
<li><a href="http://rfc.askapache.com/rfc1996/rfc1996.html">RFC 1996</a>:  A Mechanism for Prompt Notification of Zone Changes (DNS NOTIFY)</li>
<li><a href="http://rfc.askapache.com/rfc2136/rfc2136.html">RFC 2136</a>:  Dynamic Updates in the domain name system (DNS UPDATE)</li>
<li><a href="http://rfc.askapache.com/rfc2181/rfc2181.html">RFC 2181</a>:  Clarifications to the DNS Specification</li>
<li><a href="http://rfc.askapache.com/rfc2182/rfc2182.html">RFC 2182</a>:  Selection and Operation of Secondary DNS Servers</li>
<li><a href="http://rfc.askapache.com/rfc2308/rfc2308.html">RFC 2308</a>:  Negative Caching of DNS Queries (DNS NCACHE)</li>
<li><a href="http://rfc.askapache.com/rfc2317/rfc2317.html">RFC 2317</a>:  Classless IN-ADDR.ARPA delegation</li>
<li><a href="http://rfc.askapache.com/rfc2671/rfc2671.html">RFC 2671</a>:  Extension Mechanisms for DNS (EDNS0)</li>
<li><a href="http://rfc.askapache.com/rfc3597/rfc3597.html">RFC 3597</a>:  Handling of Unknown DNS Resource Record (RR) Types</li>
<li><a href="http://rfc.askapache.com/rfc3696/rfc3696.html">RFC 3696</a>:  Application Techniques for Checking and Transformation of Names</li>
<li><a href="http://rfc.askapache.com/rfc4343/rfc4343.html">RFC 4343</a>:  Domain Name System (DNS) Case Insensitivity Clarification</li>
<li><a href="http://rfc.askapache.com/rfc4592/rfc4592.html">RFC 4592</a>:  The Role of Wildcards in the Domain Name System</li>
<li><a href="http://rfc.askapache.com/rfc4892/rfc4892.html">RFC 4892</a>:  Requirements for a Mechanism Identifying a Name Server Instance</li>
<li><a href="http://rfc.askapache.com/rfc5001/rfc5001.html">RFC 5001</a>:  DNS Name Server Identifier Option (NSID)</li>
<li>RFC 5395:  Domain Name System (DNS) IANA Considerations</li>
</ul>
<p class="wikicop">This page contains content by <a rel="nofollow" href="http://en.wikipedia.org/w/index.php?title=Round_robin_DNS&#038;action=history">Author</a> of <a href="http://en.wikipedia.org/wiki/Round_robin_DNS" rel="nofollow">Article</a> from <a href="http://en.wikipedia.org/wiki/Main_Page" rel="nofollow">Wikipedia</a> and is licensed under the <a href="http://www.askapache.com/gnu-fdl.txt" rel="nofollow">GNU FDL</a>.</p>
<p><strong>Table of Contents</strong></p>
<ul>
<li><a href="#round-robin-concept">Round Robin Concept</a></li>
<li><a href="#dns-robin-dns">DNS &#8211; Domain Name System</a></li>
<li><a href="#dns-robin-round">Round Robin DNS</a></li>
<li><a href="#dns-robin-works">Efficacy of DNS Load Balancing</a></li>
<li><a href="#dns-online-tools">Live Online DNS Tools</a></li>
<li><a href="#dns-links">More Reading</a></li>
<li><a href="#dns-rfc-list">RFC&#8217;s related to DNS</a></li>
</ul>
<p><a href="http://www.askapache.com/linux-unix/dns-round-robin-rsync-over-ssh.html">DNS Round Robin Configuration using Rsync over SSH</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/linux-unix/dns-round-robin-rsync-over-ssh.html/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mirroring an Entire Site using Rsync over SSH</title>
		<link>http://www.askapache.com/security/mirror-using-rsync-ssh.html</link>
		<comments>http://www.askapache.com/security/mirror-using-rsync-ssh.html#comments</comments>
		<pubDate>Fri, 10 Apr 2009 11:40:44 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[mirror]]></category>
		<category><![CDATA[password]]></category>
		<category><![CDATA[rsync]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=2581</guid>
		<description><![CDATA[<p><a href="http://www.askapache.com/security/mirror-using-rsync-ssh.html" class="IFL"><img src="/wp-content/uploads/2009/04/mirror_buildings.jpg" alt="Website Mirrors with Rsync" title="Website Mirrors with Rsync" width="300" height="201" /></a><strong>Sometimes there is an urgent need</strong> for creating an exact duplicate or "mirror" of a web site on a separate server.  This could be needed for creating Round Robin Setups, Load-Balancing, Failovers, or for just plain vanilla backups.  In the past I have used a lot of different methods to copy data from one server to another, including creating an archive of the whole directory and then using scp to send the file over, creating an archive and then encrypting it and then sending that file over using ftp, <a href="http://curl.askapache.com/">curl</a>, etc., and my <strong>persistence at learning new ways to do things has paid off</strong> because now I use rsync to keep an exact replica of the entire directory on an external server, without having to use all the CPU and resources of other mirroring methods.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/security/mirror-using-rsync-ssh.html" class="IFL"><img src="/wp-content/uploads/2009/04/mirror_buildings.jpg" alt="Website Mirrors with Rsync" title="Website Mirrors with Rsync" width="300" height="201" /></a><strong>Sometimes there is an urgent need</strong> for creating an exact duplicate or &#8220;mirror&#8221; of a web site on a separate server.  This could be needed for creating Round Robin Setups, Load-Balancing, Failovers, or for just plain vanilla backups.  In the past I have used a lot of different methods to copy data from one server to another, including creating an archive of the whole directory and then using scp to send the file over, creating an archive and then encrypting it and then sending that file over using ftp, <a href="http://curl.askapache.com/">curl</a>, etc., and my <strong>persistence at learning new ways to do things has paid off</strong> because now I use rsync to keep an exact replica of the entire directory on an external server, without having to use all the CPU and resources of other mirroring methods.<br class="C" /></p>
<p>For this article I will show how I setup a web mirror of <var>z.askapache.com</var> from my DreamHost server to my HostGator Server.  For the transfer and synchronization of the directories we will be using rsync over SSH.  We will also be automating this task using a cronjob with no user-interaction, so creating public and private keys for the ssh will be neccessary.  Finally, I provide a simple shell script that prevents anyone from logging into your account with the created keys for any purpose other than to rsync.</p>
<p><br class="C" /><strong>Table of Contents</strong></p>
<ol>
<li><a href="#rsync-mirror">Rsync Synchronization Magic</a></li>
<li><a href="#site-mirror-rsync-ssh">Securing Rsync with SSH</a></li>
<li><a href="#site-mirror-ssh-keygen">Generate Keys with No Password</a></li>
<li><a href="#ssh-config-file">Custom SSH Connection Info</a></li>
<li><a href="#ssh-crontab-rsync">Creating Cronjob for Synchronization</a></li>
<li><a href="#secure-ssh-keys">Only Allow rsync</a></li>
<li><a href="#debug-ssh-rsync">Rsync/SSH Debugging and Stats</a></li>
<li><a href="#rsync-algorithm">Rsync Algorithm</a></li>
</ol>
<h2><a id="rsync-mirror" name="rsync-mirror"></a>Rsync Synchronization Magic</h2>
<div><a class="IFL" href="http://rsync.samba.org/"><img src="/wp-content/uploads/2009/04/200px-newrsynclogo.jpg" alt="rsync" title="rsync" width="200" height="125" /></a></p>
<dl>
<dt><strong>rsync</strong></dt>
<dd><a href="http://rsync.samba.org/">rsync</a> is an <a href="http://www.opensource.org/">open source</a> file transfer program for Unix systems that uses the &#8220;rsync algorithm&#8221; which provides a very fast method for synchronizing files and directories from one location to another while minimizing data transfer using delta encoding when appropriate. An important feature of rsync not found in most similar programs/protocols is that the mirroring takes place with only one transmission in each direction.. It does this by sending just the differences in the files across the link, without requiring that both sets of files are present at one of the ends of the link beforehand. </dd>
</dl>
<p><br class="C" /></div>
<h2><a id="site-mirror-rsync-ssh" name="site-mirror-rsync-ssh"></a>Securing Rsync with SSH</h2>
<p>I NEVER transfer any unencrypted data around unless that data is transported encrypted and to a trusted recipient, (<em>I use HTTPS for WordPress administration</em>) and I haven&#8217;t had time to probe the HostGator system for security issues yet, so right away I decided I needed an automated way to securely transfer z.askapache.com files TO hostgator, while not allowing my hostgator account access back on my main server.  So if the hostgator account were to get hacked somehow, the cracker/spammer wouldn&#8217;t have access back to my main server.</p>
<h2><a id="site-mirror-ssh-keygen" name="site-mirror-ssh-keygen"></a>Generate Keys with No Password</h2>
<p>First I created a private key, specifically a passwordless host key, meaning to gain access with ssh you only need to supply the key, not a password+key like normal.</p>
<pre class='brushbash'>
[local@dreamhost] $ mkdir -p ~/.ssh &#038;&#038; chmod 700 ~/.ssh
&nbsp;
# Create the public and private keys
# public key at: z.askapache-hostgator.id_rsa.pub
# private key at: z.askapache-hostgator.id_rsa
[local@dreamhost] $ ssh-keygen -t rsa -b 2048 -f ~/.ssh/z.askapache-hostgator.id_rsa
&nbsp;
# add the public key to remote hosts ~/.ssh/authorized_keys file
[local@dreamhost] $ ssh-copy-id -i ~/.ssh/z.askapache-hostgator.id_rsa.pub remoteuser@remotehost
&nbsp;
# or use scp + ssh to add the public key
[local@dreamhost] $ scp ~/.ssh/z.askapache-hostgator.id_rsa.pub remoteuser@remotehost:/home/remoteuser/
[local@dreamhost] $ ssh remoteuser@remotehost
[gatoraskapache@gator] $ mkdir -p ~/.ssh &#038;&#038; chmod 700 ~/.ssh
[gatoraskapache@gator] $ cat ~/z.askapache-hostgator.id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys
[gatoraskapache@gator] $ chmod 600 ~/.ssh/authorized_keys
</pre>
<h2><a id="ssh-config-file" name="ssh-config-file"></a>Custom SSH Connection Info</h2>
<p>This helps alot, by adding this to the very top of my ~/.ssh/config file I don&#8217;t have to add all this stuff to the rsync command-line.  Basically when I reference connecting to the host &#8216;gator&#8217; it uses all these options.  Very helpful and you can add as many entries as you want.</p>
<pre class='brushbash'>
Host gator
   IdentityFile ~/.ssh/z.askapache-hostgator.id_rsa
   Port 2222
   Protocol 2
   User gatoraskapache
   HostName gator555.hostgator.com
   PasswordAuthentication no
</pre>
<h2><a id="ssh-crontab-rsync" name="ssh-crontab-rsync"></a>Creating Cronjob for Synchronization</h2>
<p>This cronjob runs every 30 minutes, copying all modified files from my local directory <code>~/z.askapache.com/</code> to the remote directory <code>~/public_html/z/</code>.  First I backup the current crontab, then I edit the crontab and add this.</p>
<p><kbd>crontab -l > .crontab-`date +%F.backup`; crontab -e</kbd></p>
<pre class='brushhtaccess'>
*/30 * * * * /usr/bin/rsync -e &#039;ssh&#039; -rt &#45;-delete ~/z.askapache.com/ gator:&#039;~/public_html/z/&#039; 1&gt;/dev/null
@midnight /usr/bin/find ~/z.askapache.com/ -type d ! -perm 755 -exec chmod 755 {} \; 1&gt;/dev/null
@midnight /usr/bin/find ~/z.askapache.com/ -type f ! -perm 644 -exec chmod 644 {} \; 1&gt;/dev/null
</pre>
<p>Those 2 find commands scheduled to run at midnight simply fix and permissions on files and directories in my static folder.  They are all static files so there is no reason they need to have any other permission.</p>
<h2><a id="secure-ssh-keys" name="secure-ssh-keys"></a>Only Allow rsync</h2>
<p>This is SWEET!  If you like candy that is..  It&#8217;s called each time anything logs into your machine using the password less key we created above, and it simple checks what command the login process is attempting to issue.  To set this up you need to edit the ~/.ssh/authorized_keys file on the remote host and prefix your public key that you added with a command directive to execute a script:</p>
<pre class='brushbash'>
command="/home/remoteuser/validate-rsync.sh" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAwBhj6UCS7JbJ08C8pWJqCh2iXZMN7tXpYZh47f4gZZBwrNHZQ== localuser@dreamhost
</pre>
<h3>validate-rsync.sh</h3>
<p>For rsync requests it will always be <code>rsync &#45;-server</code> at the start of the command, so if the command is anything else then this script:</p>
<ol>
<li>Sends you an email notifying you somethings up..</li>
<li>Moves the <code>~/.ssh</code> folder to <code>~/.locked-ssh</code></li>
<li>Adds cronjob to move the folder back in about an hour.</li>
</ol>
<pre class='brushbash'>
#!/bin/bash
# Author: http://www.askapache.com
# Version: 1.2
# Date: 04-08-2009
&nbsp;
# If the command used to login to ssh correctly starts with &#039;rsync &#45;-server&#039;
# then exit this script and dont process the rest of the script
case "$SSH_ORIGINAL_COMMAND" in &#039;rsync &#45;-server&#039;*) exit 0; ;; esac;
&nbsp;
# the home directory where the .ssh folder is located
H=/home/remoteuser
&nbsp;
# if there is a locked ssh folder, kill the rsync and die
[[ -d $H/.lssh ]] &#038;&#038; echo "REJECTED" &#038;&#038; exit 1
&nbsp;
EMAIL=webmaster@askapache.com # notified about locked status
OC=$H/old-crontab.txt # the original crontab
NC=$H/new-crontab.txt #the new crontab
&nbsp;
# When to unlock the rsync
UNLOCK_AT=$(( date +%M\ %k &#45;-date=&#039;30 minute 1 hour&#039; ))
&nbsp;
# move the .ssh to .lssh which locks all key-logins
mv $H/.ssh $H/.lssh
&nbsp;
# mail a notice to the boss
echo $SSH_CONNECTION | mail -s &#039;RSYNC LOCKED!!!&#039; "$EMAIL"
&nbsp;
# subshell backs-up crontab then deletes active cron
(

 crontab -l &gt; $OC &&gt;/dev/null || echo -n #backup current crontab
 crontab -r &gt;/dev/null 2&gt;&#038;1 || echo -n # delete current crontab
)
&nbsp;
# subshell creates new crontab combined with old crontab
(
 # create new crontab
 echo -en "MAILTO=&#039;${EMAIL}&#039;\n${UNLOCK_AT} * * * mv $H/.lssh $H/.ssh" &gt;&gt; $NC
 echo -n " &#038;&#038; date|mail -s &#039;UNLOCKED!!!&#039; &#039;${EMAIL}&#039; &#038;&#038; crontab $OC || rm $OC &#038;&#038; rm $OC" &gt;&gt; $NC

 # add old crontab to new crontab minus any MAILTO lines
 cat $OC | sed &#039;/^MAILTO/d&#039; &gt;&gt; $NC

 # load the new crontab and if it doesnt work notify boss
 crontab $NC || echo "manually mv .lssh to .ssh" mail -s &#039;CRONTAB PROBLEM!!!&#039; "$EMAIL"

 # remove new crontab
 rm $NC
)
&nbsp;
exit $?
</pre>
<p><strong>Here is the cronjob entry</strong> it creates&#8230; This will enable the rsync again by moving the folder back, then it mails you to alert you that its back up, and finally the original crontab is restored.</p>
<pre class='brushbash'>
MAILTO="askapache@gmail.com"
03 9 * * * mv ~/.locked-ssh ~/.ssh &#038;&#038; date|mail -s &#039;RUNLOCKED!!!&#039; "webmaster@askapache.com" &#038;&#038; crontab ~/old-crontab.txt
</pre>
<h2><a id="debug-ssh-rsync" name="debug-ssh-rsync"></a>Rsync/SSH Debugging and Stats</h2>
<p>Adding the option -v to the ssh command, ie <kbd>rsync -e 'ssh -vv'</kbd> will give you a lot of debugging info.</p>
<p>By adding &#8211;stats to your rsync command you can get a detailed look at its efficacy.</p>
<pre class='brushhtaccess'>
Number of files: 14900
Number of files transferred: 0
Total file size: 1456832331 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 320551
File list generation time: 17.393 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 320571
Total bytes received: 20
&nbsp;
sent 320571 bytes  received 20 bytes  17329.24 bytes/sec
total size is 1456832331  speedup is 4544.21
</pre>
<h2><a id="rsync-algorithm" name="rsync-algorithm"></a>Rsync Algorithm</h2>
<p>The rsync utility uses an algorithm (invented by the Australian computer programmer Andrew Tridgell) for efficiently transmitting a structure (such as a file) across a communications link when the receiving computer already has a different version of the same structure.</p>
<p>The recipient splits its copy of the file into fixed-size non-overlapping chunks, of size S, and computes two checksums for each chunk: the MD4 hash, and a weaker &#8216;rolling checksum&#8217;. It sends these checksums to the sender. Version 30 of the protocol (released with rsync version 3.0.0) now uses MD5 hashes rather than MD4.</p>
<p>The sender computes the rolling checksum for every chunk of size S in its own version of the file, even overlapping chunks. This can be calculated efficiently because of a special property of the rolling checksum: if the rolling checksum of bytes n through n + S − 1 is R, the rolling checksum of bytes n + 1 through n + S can be computed from R, byte n, and byte n + S without having to examine the intervening bytes. Thus, if one had already calculated the rolling checksum of bytes 1–25, one could calculate the rolling checksum of bytes 2–26 solely from the previous checksum, and from bytes 1 and 26.</p>
<p>The rolling checksum used in rsync is based on Mark Adler&#8217;s adler-32 checksum, which is used in zlib, and which itself is based on Fletcher&#8217;s checksum.  The sender then compares its rolling checksums with the set sent by the recipient to determine if any matches exist. If they do, it verifies the match by computing the MD4 checksum for the matching block and by comparing it with the MD4 checksum sent by the recipient.</p>
<p>The sender then sends the recipient those parts of its file that did not match any of the recipient&#8217;s blocks, along with assembly instructions on how to merge these blocks into the recipient&#8217;s version. In practice, this creates a file identical to the sender&#8217;s copy. However, it is in principle possible that the recipient&#8217;s copy differs at this point from the sender&#8217;s: this can happen when the two files have different chunks that nonetheless possess the same MD4 hash and rolling checksum; the chances for this to happen are in practice extremely remote.</p>
<p>If the sender&#8217;s and recipient&#8217;s versions of the file have many sections in common, the utility needs to transfer relatively little data to synchronize the files.</p>
<p>While the rsync algorithm forms the heart of the rsync application that essentially optimizes transfers between two computers over TCP/IP, the rsync application supports other key features that aid significantly in data transfers or backup. They include compression and decompression of data block by block using zlib at sending and receiving ends, respectively, and support for protocols such as ssh that enables encrypted transmission of compressed and efficient differential data using rsync algorithm. Instead of ssh, stunnel can also be used to create an encrypted tunnel to secure the data transmitted.</p>
<p>Finally, rsync is capable of limiting the bandwidth consumed during a transfer, a useful feature that few other standard file transfer protocol offer.</p>
<p class="wikicop">This page contains content by <a rel="nofollow" href="http://en.wikipedia.org/w/index.php?title=Rsync&#038;action=history">Author</a> of <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow">Article</a> from <a href="http://en.wikipedia.org/wiki/Main_Page" rel="nofollow">Wikipedia</a> and is licensed under the <a href="http://www.askapache.com/gnu-fdl.txt" rel="nofollow">GNU FDL</a>.</p>
<p><a href="http://www.askapache.com/security/mirror-using-rsync-ssh.html">Mirroring an Entire Site using Rsync over SSH</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/security/mirror-using-rsync-ssh.html/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Password Protection Plugin Status</title>
		<link>http://www.askapache.com/htaccess/password-protection-plugin-status.html</link>
		<comments>http://www.askapache.com/htaccess/password-protection-plugin-status.html#comments</comments>
		<pubDate>Sun, 01 Mar 2009 17:39:57 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress Plugins]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[.htaccess plugin]]></category>
		<category><![CDATA[askapache]]></category>
		<category><![CDATA[password protection]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=1966</guid>
		<description><![CDATA[<p><a class="IFL" href="/wp-content/uploads/2009/03/apache-security-model-tall1.png"><img src="/wp-content/uploads/2009/03/apache-security-model-tall1-250x123.png" alt="Apache Security Model - In Color" title="apache-security-model-wide" width="250" height="123" /></a>I wanted to address why the update to the AskApache Password Protection plugin didn't happen pre-2009 as I had hoped.. Mostly due to my job but I thought I could at least fill you in.  Oh and this is going to get very boring very fast, unless you're ready to rumble in the zone.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p>I wanted to address why the update to the AskApache Password Protection plugin didn&#8217;t happen pre-2009 as I had hoped.. Mostly due to my job but I thought I could at least fill you in.  Oh and this is going to get very boring very fast, unless you&#8217;re ready to rumble in the zone.</p>
<h2>File Permissions!</h2>
<p>The main issue with the password protection plugin working for some people and not others is due to <a title="detailed file permission article" href="http://www.askapache.com/security/chmod-stat.html">file permission configurations</a>.  WordPress is simply a group of .php files saved on your server.  The actual program that is in fact running WordPress is the <a title="SuEXEC and php.cgi" href="http://www.askapache.com/htaccess/php-cgi-redirect_status.html">PHP interpreter</a>, which is in turn controlled by the Apache Server.  Almost all computers are running at least 2 servers, the Web Server which serves and displays your files, and a FTP server.</p>
<p><a class="IFL" href="/wp-content/uploads/2009/03/apache-security-model-tall1.png"><img src="/wp-content/uploads/2009/03/apache-security-model-tall1-250x123.png" alt="Apache Security Model - In Color" title="apache-security-model-wide" width="250" height="123" /></a>  Here&#8217;s a detailed look at the Apache Security Model, from <a href="http://www.apachesecurity.net/blog/2009/02/apache_security_model.html">ApacheSecurity.net</a>, a blog maintained by <em>Ivan Ristic</em>, the author of <a href="http://www.modsecurity.org/">ModSecurity</a>.<br class="C" /></p>
<p>The problem is happening because when you login to your FTP server with your username and password, the files that you upload are then  owned by that username and password, which is almost always an actual user account on the server system.  But the Apache Server is an executable file itself, and it is not owned by your FTP username, for security reasons.  Apache controls the PHP Interpreter, which parses and executes the WordPress and plugin files as a separate user.  ( <a href="http://httpd.apache.org/docs/trunk/suexec.html">SuEXEC</a>, <a href="http://httpd.apache.org/docs/trunk/misc/security_tips.html">Apache Security Tips</a> ) </p>
<p>So what happens is the <code>askapache-password-protect.php</code> file saved on your server and is owned by the user that created it (if you downloaded it to your computer then used ftp to transfer, your ftp user owns it..  if you used a php downloader script, then the php process owner owns it)   So when you click on the Run Tests button from the WordPress administration website what you are doing is sending a request via HTTP to your Apache Server process, which sees the requested file is .php so it then runs the php interpreter to execute the askapache-password-protect.php file, then that file uses programming to attempt and write/modify a file in your blog&#8217;s root directory.</p>
<h2>Process Owner vs. File Owner</h2>
<p>So who owns your blog&#8217;s root directory?  Your ftp user account/ you do..   but who owns the process that is trying to write/modify a file that is owned by your ftp user?  The PHP Process that is actually executing the file access/write requests.  This is the core way that 99% of all web sites get cracked into.. All these malicious robots and exploit bots do is attempt to write a file onto your server so that it can then be used to take over your site.  If they can save a file on your blog&#8217;s directory (uploads, insecure plugin code, not filtering user input, etc..) it inherits the permissions of the process that actually wrote the data bits onto the hard-drive.</p>
<p>So some server-admins/web hosts configure the php interpreter to not have write access anywhere except for a couple neccessary locations like /tmp.  They have auto-installation&#8217;s available through their online web panels, meaning instead of executing .php scripts in your user directory as the php process they force you to use, they can bypass all that because the installation scripts they use are all on their systems, not on your &#8220;locked-down&#8221; cluster.</p>
<p>This is the fundamental security battle that network server security is all based on..   Apache is owned by a powerful user because it owns the server process, so apache is often run as the user dhapache or nobody..  If a cracker is able to find a way to get a file saved on your server with the dhapache user as the owner then they&#8217;ve basically just gotten control of the whole thing.  When you upload a file to your server using the add attachment form in wordpress, the file first goes through the dhapache user which passes the file to the php process owner which has much less permissions.  Apache has been in open-source development for many many years now, its the safest most secure server in the world, windows servers are hackable, apache servers are hacked usually only when the sysadmin configures it wrong or accidentally.</p>
<p>Believe it or not, as confusing as my feeble explanation was, this is only like .1% of whats going on.. I&#8217;ve basically spent the last several months developing the new version specifically to be able to work no matter what configuration you have.  What I ended up doing was finding ways to bypass this security on a couple hosting providers that are setup in this way, but even though I got it to work in most instances it basically was hacking their systems, and if I published that code to automatically bypass web-hosts security setups I think I&#8217;d be in big trouble and they would just close those specific holes and the plugin would not work again.   So I decided instead of exploiting host-specifics hacks to get the plugin to work that I would focus on the method that WordPress sorta uses.  The code they have now (2.8 bleeding-edge) still isn&#8217;t where it needs to be, but this is some difficult stuff and they have a brilliant start, it&#8217;ll work.. just a question of when.</p>
<h2><code>wp-admin/includes/file.php</code></h2>
<p>Ok so this function <code>get_filesystem_method</code> is a brilliant bit of code that would&#8217;ve been beyond my current PHP skills to come up with.  It determines which if any of the following methods can be used to modify files on your server from within WordPress, which is exactly what the new version of the passpro plugin needs to use.   The first test simply creates a file from within php using wp_tempnam, a function that attempts to locate and write to a temporary location on your server that has the best chance of having write access.  If it is successfully created (this code assumes that it will be, something they need to fix) then the fileowner (uses stat internally) of the temp file just created is compared to the owner of the php script&#8230;  Normally this works and then the plugin woks too, but on some hosts the script is running as a separate user than that of the file which means you can&#8217;t directly access the local file system.  That is what is occurring for most of you who experience permission problems while testing the plugin.  There are thousands of caveats for each little part depending on your php version, php setup, server setup, server version, which Server API you are using, the type of SAPI being used, and on and on..</p>
<pre>
function get_filesystem_method($args = array()) {
  $method = false;
  if( function_exists(&#039;getmyuid&#039;) &#038;&#038; function_exists(&#039;fileowner&#039;) ){
    $temp_file = wp_tempnam();
    if ( getmyuid() == fileowner($temp_file) ) $method = &#039;direct&#039;;
    unlink($temp_file);
  }
  if ( ! $method &#038;&#038; isset($args[&#039;connection_type&#039;]) &#038;&#038; &#039;ssh&#039; == $args[&#039;connection_type&#039;] &#038;&#038; extension_loaded(&#039;ssh2&#039;) )
          $method = &#039;ssh2&#039;;
  if ( ! $method &#038;&#038; extension_loaded(&#039;ftp&#039;) )
          $method = &#039;ftpext&#039;;
  if ( ! $method &#038;&#038; ( extension_loaded(&#039;sockets&#039;) || function_exists(&#039;fsockopen&#039;) ) )
          $method = &#039;ftpsockets&#039;; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
  return apply_filters(&#039;filesystem_method&#039;, $method);
}
</pre>
<h2>Enumerating Permissions can be Annoying</h2>
<p>This was part of some tests I did to see what kind of access I had with the very helpful posix functions which are very accurate as well since they were designed for a system with file permissions, ie. not Win.  Don&#8217;t ask me how because I won&#8217;t tell you, but on one of the hosts I was testing on that did not allow direct access I was able to get the Apache server running as dhapache to erroneously write a file into my users blog directory.  This is a big security no-no and I now have my .htaccess file written into the blog directory where it should go, but instead of my php script&#8217;s user having write access to the file so I can modify it, its owned by dhapache!  Because the file is owned by dhapache I shouldn&#8217;t even be allowed to know it exists, but there it is.  So the next step was to try and take ownership of the .htaccess file so that I could modify it.  I tried and tried but was unsuccessful, I couldn&#8217;t modify it so that was another dead end.  Actually it took me awhile to figure out how to remove the file from my directory.  Being that it was owned by dhapache I couldn&#8217;t delete or modify it using my php process or even through ftp/ssh!  Sysadmins regularly run find commands that search the servers for any files owned by dhapache that should not be there as this is a big red flag that someone has found a way to manipulate dhapache which could potentially lead to modifying dhapche-owned server config files.. Luckily I was able to delete it by basically running the hack again to overwrite the file.</p>
<pre>
  if ((posix_setgid(getmygid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETGID of {$file}  to " . getmygid(), 3);
  elseif ((posix_setgid(filegroup(__file__))) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETUID of {$file} to " . filegroup(__file__), 3);
  if ((posix_setegid(getmygid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETEGID of {$file} to " . getmygid(), 3);
  elseif ((posix_setegid(filegroup(__file__))) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETEGID of {$file} to " . filegroup(__file__), 3);
  if ((posix_setuid(getmyuid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETUID of {$file}  to " . getmyuid(), 3);
  elseif ((posix_setuid(get_current_user())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETUID of {$file} to " . get_current_user(), 3);
  if ((posix_seteuid(getmyuid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETEUID of {$file} to " . getmyuid(), 3);
  elseif ((posix_seteuid(get_current_user())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing SETEUID of {$file} to " . get_current_user(), 3);
  if ((chmod($file, FS_CHMOD_DIR) || chmod($file, 0776) || chmod($file, 0766) || chmod($file,
    FS_CHMOD_FILE)) !== false) $this-&gt;to_log(&#039;&#039;, 1, "Success Changing Mode of {$file}", 3);
  if ((chown($file, getmyuid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Ownership of {$file} to " . getmyuid(), 3);
  elseif ((chown($file, get_current_user())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Ownership of {$file} to " . get_current_user(), 3);
  if ((chgrp($file, getmygid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Group of {$file} to " . getmygid(), 3);
  elseif ((chgrp($file, filegroup(__file__))) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Group of {$file} to " . filegroup(__file__), 3);
  if ((chmod($file, FS_CHMOD_DIR) || chmod($file, 0776) || chmod($file, 0766) || chmod($file,
    FS_CHMOD_FILE)) !== false) $this-&gt;to_log(&#039;&#039;, 1, "Success Changing Mode of {$file}", 3);
  if ((chown($file, getmyuid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Ownership of {$file} to " . getmyuid(), 3);
  elseif ((chown($file, get_current_user())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Ownership of {$file} to " . get_current_user(), 3);
  if ((chgrp($file, getmygid())) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Group of {$file} to " . getmygid(), 3);
  elseif ((chgrp($file, filegroup(__file__))) !== false) $this-&gt;to_log(&#039;&#039;, 1,
      "Success Changing Group of {$file} to " . filegroup(__file__), 3);
  return (!$this-&gt;_fclose($fh)) ? $this-&gt;to_log(__function__ . &#039;:&#039; . __line__ .
    " Error closing {$mode} handle for {$file}", 0) : $total;
</pre>
<p>If php process isn&#8217;t allowed to write to your web directory but you have an ftp account that is, then we request your ftp username/password in wordpress and if the php process running the <code>askapache-password-protect.php</code> plugin script is allowed access to <a href="http://www.askapache.com/php/fsockopen-socket.html">raw networking sockets using fsockopen</a> then we can basically access and write to your blog&#8217;s <code>.htaccess</code> file by using php to mimick an ftp client session. There are also other protocols and options available using php if ftp/fsockopen isn&#8217;t allowed, but you run out of alternatives quick.  Using the curl extension is one option.</p>
<p>So I wrote my own ftp library for a fsockopen class I had already developed for specific test requirements in unreleased versions, so the release of the new askapache password protect plugin will work for 75% or so of the people who have trouble now.. not to mention the insane logging and debugging I&#8217;ve added while looking for the reasons some web-hosts still don&#8217;t work.  Some use custom php security modules, wrappers, and custom virtual servers that are akin to a vmware server.  So for maybe 10% of those running apache who have had problems they would still have them. I&#8217;m still playing with some ssh capability from within the plugin similar to the ftp technique..  I really hope WordPress just adds this functionality by updating their current filesystem classes..</p>
<h2>Fsockopen Payload Class</h2>
<p>Here&#8217;s what I had several versions ago.. Just sticking it up here in case anyone is curious, one cool thing this version starts to incorporate is being able to send direct data payloads across the socket so it can be used like <a href="http://metasploit.com/" title="Metasploit provides useful information to people who perform penetration testing, IDS signature development, and exploit research.">the metasploit framework</a> to send payloads of exploits, but of course we&#8217;re using it to mimick other protocols like ftp, which can be setup by feeding hex into the socket direct from a real ftp client, and piping the output. Keep in mind that this is my first time using php classes, so the learning curve has been incredible&#8230;</p>
<pre>
&lt;?php
error_log("RUNNING " . basename(__file__) . "\n");
if (!in_array(&#039;AskApache_Net&#039;, get_declared_classes()) &#038;&#038; !class_exists(&#039;AskApache_Net&#039;)):
 class AskApache_Net extends AskApachePassPro
 {
  var $_fp = null;
  var $_socket = array(&#039;protocol&#039; =&gt; &#039;1.0&#039;, &#039;method&#039; =&gt; &#039;GET&#039;, &#039;referer&#039; =&gt;
   &#039;http://www.askapache.com/&#039;, &#039;port&#039; =&gt; &#039;80&#039;, &#039;ua&#039; =&gt;
   &#039;Mozilla/5.0 (compatible; AskApache_Net/1.6; http://www.askapache.com/)&#039;, &#039;scheme&#039; =&gt;
   &#039;http&#039;, &#039;transport&#039; =&gt; &#039;&#039;, &#039;host&#039; =&gt; &#039;&#039;, &#039;user&#039; =&gt; &#039;&#039;, &#039;pass&#039; =&gt; &#039;&#039;, &#039;path&#039; =&gt; &#039;/&#039;,
   &#039;query&#039; =&gt; &#039;&#039;, &#039;fragment&#039; =&gt; &#039;&#039;);
  var $authtype = &#039;Basic&#039;;
  var $timeout = 15;
  var $_dh = &#039;&#039;;
  var $_digest = array(&#039;realm&#039; =&gt; &#039;&#039;, &#039;nonce&#039; =&gt; &#039;&#039;, &#039;uri&#039; =&gt; &#039;&#039;, &#039;algorithm&#039; =&gt; &#039;MD5&#039;,
   &#039;qop&#039; =&gt; &#039;auth&#039;, &#039;opaque&#039; =&gt; &#039;&#039;, &#039;domain&#039; =&gt; &#039;&#039;, &#039;nc&#039; =&gt; &#039;00000001&#039;, &#039;cnonce&#039; =&gt;
   &#039;82d057852a9dc497&#039;, &#039;A1&#039; =&gt; &#039;&#039;, &#039;A2&#039; =&gt; &#039;&#039;, &#039;response&#039; =&gt; &#039;&#039;);
  var $_ACLF = "\r\n";
  var $_request_body = &#039;&#039;;
  var $_request_headers = array();
  var $_response_headers = array();
  var $my_headers;
  var $_response_header = &#039;&#039;;
  var $_response_protocol = &#039;&#039;;
  var $_response_version = &#039;&#039;;
  var $_response_code = &#039;&#039;;
  var $_response_message = &#039;&#039;;
  var $_response_body = &#039;&#039;;
  var $_errs = array(3 =&gt; &#039;Socket creation failed&#039;, 4 =&gt; &#039;DNS lookup failure&#039;, 5 =&gt;
   &#039;Connection refused or timed out&#039;, 111 =&gt; &#039;Connection refused&#039;, 113 =&gt;
   &#039;No route to host&#039;, 110 =&gt; &#039;Connection timed out&#039;, 104 =&gt; &#039;Connection reset by client&#039;);

  /**
   * AskApache_Net::AskApache_Net()
   */
  function AskApache_Net()
  {
   return $this-&gt;__construct();
  }

  /**
   * AskApache_Net::__destruct()
   */
  function __destruct()
  {
   $this-&gt;_timer(&#039;class&#039;);
   return true;
  }

  /**
   * AskApache_Net::__construct()
   */
  function __construct()
  {
   $this-&gt;_timer(&#039;class&#039;);
   $this-&gt;_ACLF = chr(13) . chr(10);
   @set_time_limit(60);
   return true;
  }

  /**
   * AskApache_Net::hsockit()
   */
  function hsockit($URI)
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   $this-&gt;_socket[&#039;method&#039;] = &#039;HEAD&#039;;
   return $this-&gt;sockit($URI);
  }

  /**
   * AskApache_Net::sockit()
   */
  function sockit($URI = &#039;&#039;)
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   if (!$this-&gt;_build_sock($URI)) return $this-&gt;msg(__function__ . &#039;:&#039; . __line__,
     "Failed!", 0);
   if (!$this-&gt;_connect()) return $this-&gt;msg(__function__ . &#039;:&#039; . __line__, "Failed!", 0);
   $this-&gt;_build_request();
   if (!$this-&gt;_build_request()) return $this-&gt;msg(__function__ . &#039;:&#039; . __line__,
     "Failed!", 0);
   if (!$this-&gt;_tx()) return $this-&gt;msg(__function__ . &#039;:&#039; . __line__, "tx Failed!", 0);
   if (!$this-&gt;_rx()) return $this-&gt;msg(__function__ . &#039;:&#039; . __line__, "rx Failed!", 0);
   if (!$this-&gt;_disconnect()) return $this-&gt;msg(__function__ . &#039;:&#039; . __line__,
     "disconnect Failed!", 0);
   if ((bool)$this-&gt;net_debug === true) {
    foreach (array(&#039;out_payload&#039;, &#039;_request_body&#039;, &#039;_response_header&#039;, &#039;_response_body&#039;) as
     $nam) {
     if (is_array($this-&gt;$nam)) {
      if (sizeof($this-&gt;$nam) &gt; 1) {
       echo "\n\n{$nam}\n";
       print_r($this-&gt;$nam);
      }
     } else {
&nbsp;
      if (!empty($this-&gt;$nam)) {
       echo "\n\n{$nam}\n";
       echo $this-&gt;$nam;
      }
     }
    }
    $this-&gt;tcp_trace(1);
   }
   return (int)$this-&gt;_response_code;
  }

  /**
   * AskApache_Net::_build_sock()
   */
  function _build_sock($url)
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   $socket_info = &#038;$this-&gt;_socket;
   if (!$u_bits = parse_url($url)) return false;
   if (empty($u_bits[&#039;method&#039;])) $u_bits[&#039;method&#039;] = &#039;GET&#039;;
   if (empty($u_bits[&#039;protocol&#039;])) $u_bits[&#039;protocol&#039;] = &#039;1.0&#039;;
   if (empty($u_bits[&#039;host&#039;])) $u_bits[&#039;host&#039;] = $_SERVER[&#039;HTTP_HOST&#039;];
   if (empty($u_bits[&#039;scheme&#039;])) $u_bits[&#039;scheme&#039;] = &#039;http&#039;;
   if (empty($u_bits[&#039;port&#039;])) $u_bits[&#039;port&#039;] = $_SERVER[&#039;SERVER_PORT&#039;];
   $u_bits[&#039;path&#039;] = (empty($u_bits[&#039;path&#039;]) ? &#039;/&#039; : $u_bits[&#039;path&#039;]) . (!empty($u_bits[&#039;query&#039;]) ?
    &#039;?&#039; . $u_bits[&#039;query&#039;] : &#039;&#039;);
   if (empty($u_bits[&#039;ua&#039;])) $u_bits[&#039;ua&#039;] =
     &#039;Mozilla/5.0 (compatible; AskApache_Net/1.0; http://www.askapache.com)&#039;;
   if (empty($u_bits[&#039;referer&#039;])) $u_bits[&#039;referer&#039;] = &#039;http://www.askapache.com&#039;;
   if (empty($u_bits[&#039;fragment&#039;])) unset($u_bits[&#039;fragment&#039;]);
   if (empty($u_bits[&#039;user&#039;])) unset($u_bits[&#039;user&#039;]);
   if (empty($u_bits[&#039;pass&#039;])) unset($u_bits[&#039;pass&#039;]);
   if ($u_bits[&#039;scheme&#039;] == &#039;https&#039; || $this-&gt;_socket[&#039;scheme&#039;] == &#039;https&#039;) $u_bits[&#039;transport&#039;] =
     &#039;ssl://&#039;;
   if ($u_bits[&#039;scheme&#039;] == &#039;https&#039; || $this-&gt;_socket[&#039;scheme&#039;] == &#039;https&#039;) $u_bits[&#039;port&#039;] =
     &#039;443&#039;;
   $socket_info = $this-&gt;_parse_args($u_bits, $socket_info);
   extract($socket_info, EXTR_SKIP);
   return true;
  }

  /**
   * AskApache_Net::_build_auth_header()
   */
  function _build_auth_header()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   if ($this-&gt;authtype == &#039;Basic&#039;) $this-&gt;_request_headers[] = &#039;Authorization: Basic &#039; .
     base64_encode($this-&gt;_socket[&#039;user&#039;] . ":" . $this-&gt;_socket[&#039;pass&#039;]);
   elseif ($this-&gt;authtype == &#039;Digest&#039;) {
    $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
    $this-&gt;_socket[&#039;protocol&#039;] = &#039;1.1&#039;;
    $hdr = $mtx = array();
    preg_match_all(&#039;/(\w+)=(?:"([^"]+)"|([^\s,]+))/&#039;, $this-&gt;_dh, $mtx, PREG_SET_ORDER);
    foreach ($mtx as $m) $hdr[$m[1]] = $m[2] ? $m[2] : $m[3];
    foreach ($hdr as $key =&gt; $val)
     if (array_key_exists($key, $this-&gt;_digest) &#038;&#038; !empty($val)) $this-&gt;_digest[$key] = $val;
    $this-&gt;_digest[&#039;uri&#039;] = $this-&gt;_socket[&#039;path&#039;];
    $this-&gt;_digest[&#039;A1&#039;] = md5($this-&gt;_socket[&#039;user&#039;] . &#039;:&#039; . $this-&gt;_digest[&#039;realm&#039;] .
     &#039;:&#039; . $this-&gt;_socket[&#039;pass&#039;]);
    $this-&gt;_digest[&#039;A2&#039;] = md5($this-&gt;_socket[&#039;method&#039;] . &#039;:&#039; . $this-&gt;_socket[&#039;path&#039;]);
    $this-&gt;_digest[&#039;response&#039;] = md5($this-&gt;_digest[&#039;A1&#039;] . &#039;:&#039; . $this-&gt;_digest[&#039;nonce&#039;] .
     &#039;:&#039; . $this-&gt;_digest[&#039;nc&#039;] . &#039;:&#039; . $this-&gt;_digest[&#039;cnonce&#039;] . &#039;:&#039; . $this-&gt;_digest[&#039;qop&#039;] .
     &#039;:&#039; . $this-&gt;_digest[&#039;A2&#039;]);
    $this-&gt;_request_headers[] = sprintf(&#039;Authorization: Digest username="%1$s", realm="%2$s", nonce="%3$s",&#039;.
     &#039;uri="%4$s", algorithm=%5$s, response="%6$s", qop="%7$s", nc="%8$s"%9$s%10$s&#039;,
     $this-&gt;_socket[&#039;user&#039;], $this-&gt;_digest[&#039;realm&#039;], $this-&gt;_digest[&#039;nonce&#039;], $this-&gt;
     _digest[&#039;uri&#039;], $this-&gt;_digest[&#039;algorithm&#039;], $this-&gt;_digest[&#039;response&#039;], $this-&gt;
     _digest[&#039;qop&#039;], $this-&gt;_digest[&#039;nc&#039;], !empty($this-&gt;_digest[&#039;cnonce&#039;]) ? &#039;, cnonce="&#039; .
     $this-&gt;_digest[&#039;cnonce&#039;] . &#039;"&#039; : &#039;&#039;, !empty($this-&gt;_digest[&#039;opaque&#039;]) ? &#039;, opaque="&#039; .
     $this-&gt;_digest[&#039;opaque&#039;] . &#039;"&#039; : &#039;&#039;);
   }
   return true;
  }

  /**
   * AskApache_Net::_build_request()
   */
  function _build_request()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   $this-&gt;_request_headers[] = $this-&gt;_socket[&#039;method&#039;] . " " . $this-&gt;_socket[&#039;path&#039;] .
    " HTTP/" . $this-&gt;_socket[&#039;protocol&#039;];
   if (is_array($this-&gt;my_headers) &#038;&#038; sizeof($this-&gt;my_headers) &gt; 0) $this-&gt;
     _request_headers = array_merge($this-&gt;_request_headers, $this-&gt;my_headers);
   else {
    $this-&gt;_request_headers[] = "Host: " . $this-&gt;_socket[&#039;host&#039;];
    $this-&gt;_request_headers[] = "User-Agent: " . $this-&gt;_socket[&#039;ua&#039;];
    $this-&gt;_request_headers[] = &#039;Accept: application/xhtml+xml,text/html;q=0.9,*/*;q=0.5&#039;;
    $this-&gt;_request_headers[] = &#039;Accept-Language: en-us,en;q=0.5&#039;;
    $this-&gt;_request_headers[] = &#039;Accept-Encoding: none&#039;;
    $this-&gt;_request_headers[] = &#039;Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7&#039;;
    $this-&gt;_request_headers[] = &#039;Referer: &#039; . $this-&gt;_socket[&#039;referer&#039;];
   }
   if (!empty($this-&gt;_socket[&#039;user&#039;]) &#038;&#038; !empty($this-&gt;_socket[&#039;pass&#039;])) $this-&gt;
     _build_auth_header();
   if ($this-&gt;out_payload !== false) $this-&gt;_request_body = $this-&gt;out_payload;
   else  $this-&gt;_request_body = join($this-&gt;_ACLF, $this-&gt;_request_headers) . $this-&gt;
     _ACLF . $this-&gt;_ACLF;
   return true;
  }

  /**
   * AskApache_Net::_tx()
   */
  function _tx()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   return (bool)(is_resource($this-&gt;_fp) &#038;&#038; $this-&gt;_netwrite($this-&gt;_fp, $this-&gt;
    _request_body));
  }

  /**
   * AskApache_Net::_rx()
   */
  function _rx()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   if (!is_resource($this-&gt;_fp)) return false;
   $this-&gt;_response = $this-&gt;_netread($this-&gt;_fp, 500000);
   $parts = explode($this-&gt;_ACLF . $this-&gt;_ACLF, ltrim($this-&gt;_response), 2);
   $this-&gt;_response_header = trim($parts[0]);
   $this-&gt;_response_body = trim($parts[1]);
   if (preg_match(&#039;#([^/]*)/([\d\.]+) ([\d]*?) (.*)#&#039;, $this-&gt;_response_header, $htx)) {
    $this-&gt;_response_protocol = trim($htx[1]);
    $this-&gt;_response_version = trim($htx[2]);
    $this-&gt;_response_code = trim($htx[3]);
    $this-&gt;_response_message = trim($htx[4]);
   }
   if (preg_match_all(&#039;#([^:]+)\:?(.*)#&#039;, str_replace($htx, &#039;&#039;, $this-&gt;_response_header),
    $mtx, PREG_SET_ORDER)) {
    foreach ($mtx as $m) {
     $this-&gt;_headers[strtolower(trim($m[1]))] = trim($m[2]);
     if (preg_match(&#039;/(WWW|Proxy)-Authenticate:.*Digest/i&#039;, trim($m[1]))) $this-&gt;_dh =
       trim($m[1]);
    }
   }
   return true;
  }

  /**
   * AskApache_Net::tcp_trace()
   */
  function tcp_trace($p = false)
  {
   $this-&gt;_timer(__function__ );
   $ret = join("\n", array_merge((array )$this-&gt;_request_headers, array(&#039;&#039;), (array )$this-&gt;
    _response_headers));
   if ($p !== false) {
    echo $ret;
    $ret = true;
   }
   $this-&gt;_timer(__function__ );
   return $ret;
  }

  /**
   * AskApache_Net::_get_ip()
   */
  function _get_ip($host)
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
&nbsp;
   if (!preg_match(&#039;/^[\t ]*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+[\t ]*$/&#039;, $host)) $hostip =
     gethostbyname($host);
   $ip = ($hostip == $host) ? $host : long2ip(ip2long($hostip));
   return $ip;
  }

  /**
   * AskApache_Net::_connect()
   */
  function _connect()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   if (false === ($this-&gt;_fp = fsockopen($this-&gt;_get_ip($this-&gt;_socket[&#039;host&#039;]), $this-&gt;
    _socket[&#039;port&#039;], $errno, $errstr, $this-&gt;timeout)) || !is_resource($this-&gt;_fp)) {
    $err = (array_key_exists($errno, $this-&gt;_errs)) ? $this-&gt;_errs[$errno] :
     &#039;Connection failed&#039;;
    return $this-&gt;msg(__function__ . &#039;:&#039; . __line__ . " Fsockopen failed! [{$errno}] {$err} ({$errstr})",
     0);
   }
   if (function_exists("socket_set_timeout")) socket_set_timeout($this-&gt;_fp, $this-&gt;
     timeout);
   elseif (function_exists("stream_set_timeout")) stream_set_timeout($this-&gt;_fp, $this-&gt;
     timeout);
   usleep(10000);
   return true;
  }

  /**
   * AskApache_Net::_disconnect()
   */
  function _disconnect()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   if (is_resource($this-&gt;_fp)) return $this-&gt;_fclose($this-&gt;_fp);
   else  $this-&gt;_fp = null;
   return true;
  }

  /**
   * AskApache_Net::get_response_headers()
   */
  function get_response_headers($header = false)
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   if ($header !== false &#038;&#038; array_key_exists($header, $this-&gt;_response_headers)) return $this-&gt;
     _response_headers[$header];
   return $this-&gt;_response_headers;
  }

  /**
   * AskApache_Net::get_response_body()
   */
  function get_response_body()
  {
   $this-&gt;msg(__function__ . &#039;:&#039; . __line__, 3);
   return $this-&gt;_response_body;
  }

  /**
   * AskApache_Net::_netread()
   */
  function _netread(&#038;$fh, $ts = 50000000, $bs = 124)
  {
   $this-&gt;_timer(__function__ );
   for ($d = $b = &#039;&#039;, $rt = $at = $r = 0; ($fh !== false &#038;&#038; !feof($fh) &#038;&#038; $b !== false &#038;&#038;
    $at &lt; 50000000 &#038;&#038; $rt &lt; $ts); $r = $ts - $rt, $bs = (($bs &gt; $r) ? $r : $bs), $this-&gt;
    _timer("R: {$rt}"), $b = fread($fh, $bs), $br = strlen($b), $d .= $b, $this-&gt;_timer("R: {$rt}"),
    $rt += $br, $at++, $this-&gt;msg("[RT: {$rt}]\t[BR: {$br}" . (($ts != 50000000) ? "]\t\t [{$r} / {$ts}]" :
    " : {$bs}]\t[{$at}]"))) ;
   $this-&gt;_timer(__function__ );
   return ((strlen($d) != 0)) ? $d : false;
  }

  /**
   * AskApache_Net::_netwrite()
   */
  function _netwrite(&#038;$fh, $d = &#039;&#039;, $bs = 512)
  {
   $this-&gt;_timer(__function__ );
&nbsp;
   for ($bw = $wt = $at = 0, $dat = &#039;&#039;, $ts = strlen($d); ($fh !== false &#038;&#038; $bw !== false &#038;&#038;
    $at &lt; 50000000 &#038;&#038; $wt &lt; $ts); $r = $ts - $wt, $bs = (($bs &gt; $r) ? $r : $bs), $dat =
    substr($d, $wt, $bs), $bw = fwrite($fh, $dat), $wt += $bw, $this-&gt;msg("[WT: {$wt}]\t[BW: {$bw}]\t\t[I: {$r} / {$ts}:{$bs}] - {$at}"),
    $at++) ;
   $this-&gt;msg("[WT: {$wt}]\t[BW: {$bw}]\t\t[I: {$r} / {$ts}:{$bs}] - {$at}");
   $this-&gt;_timer(__function__ );
   return ($wt == $ts) ? true : false;
  }
 }
endif;
?&gt;
</pre>
<p>So I decided to finally give in to what I&#8217;ve been avoiding all along and added a php-software-based method that will work on everycomputer, windows, blackberrys, etc.. That took me about 15minutes as its just a few lines of code.. The problem I have with it is that php is what is actually controlling the sending, receiving, and verifying of the authentication headers instead of using the builtin super-secure apache method.</p>
<p>Here&#8217;s how you would block someone using the apache/askapache way:</p>
<pre>
[Exploit Request] =&gt; ([BLOCKED]-AskApache)
</pre>
<p>This prevents the exploit from even reaching PHP, saving your computer a lot of CPU/memory and bandwdith, and obviously can&#8217;t exploit wordpress if php isn&#8217;t even loading.</p>
<p>Here&#8217;s how the php-software-based method blocks the same request:</p>
<pre>
[Exploit Request] =&gt; (AskApache) =&gt; (PHP) =&gt; (WordPress) =&gt; ([BLOCKED]-askapache-password-protect.php)
</pre>
<p>So the last bit of programming and research I&#8217;m doing at the moment is how to cause the askapache-password-protect plugin to execute as soon as possible, ideally it would execute before WordPress starts..   And I am still crazy swamped at work, this was the longest non-posting period of the blog to date!</p>
<p><a href="http://www.askapache.com/htaccess/password-protection-plugin-status.html">Password Protection Plugin Status</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/htaccess/password-protection-plugin-status.html/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ultimate Htaccess Tutorial for .htaccess files</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[Apache]]></category>
		<category><![CDATA[Apache Modules]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[DreamHost]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Linux Unix BSD]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Web Design]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[Web Tools]]></category>
		<category><![CDATA[Webmaster]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[.htaccess examples]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[Files]]></category>
		<category><![CDATA[FilesMatch]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[htaccess guide]]></category>
		<category><![CDATA[htaccess help]]></category>
		<category><![CDATA[htaccess howto]]></category>
		<category><![CDATA[htaccess rewrite]]></category>
		<category><![CDATA[htaccess tricks]]></category>
		<category><![CDATA[htaccess tutorial]]></category>
		<category><![CDATA[httpd]]></category>
		<category><![CDATA[litespeed]]></category>
		<category><![CDATA[Mod_Security]]></category>
		<category><![CDATA[rewritecond]]></category>
		<category><![CDATA[rewriterule]]></category>
		<category><![CDATA[sample .htaccess]]></category>
		<category><![CDATA[seo secrets]]></category>
		<category><![CDATA[SetEnvIf]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[ultimate htaccess]]></category>

		<guid isPermaLink="false">http://www.askapache.com.com/htaccess/htaccesselite-ultimate-htaccess-article.html</guid>
		<description><![CDATA[<p><a class="IFL" href="http://www.askapache.com/htaccess/htaccess.html" title="AskApache .htaccess Tutorial"><img src="/wp-content/uploads/2008/08/htaccess-up.png" alt=".htaccess tutorial and htaccess sample" title=".htaccess tutorial and htaccess sample" width="236" height="301" /></a>This is not an <em>introduction to <code>.htaccess</code></em>...  <strong>This is the evolution of <tt>.htaccess</tt></strong>... The <strong>BEST</strong>, the <strong>ORIGINAL</strong>, the <strong>NEWEST</strong>, and the most <strong>HIGHEST, FLYEST</strong> .htaccess tricks I can find.<br /><br />Originally known as the <em>"Ultimate .htaccess Guide"</em>, its changed over the years by adding new <em>.htaccess tricks</em> and <em><a href="http://www.askapache.com/htaccess/htaccess.html#htaccess-code-examples">.htaccess examples</a></em> to it..   I also add my <a href="http://www.askapache.com/htaccess/htaccess.html#favorite-htaccess">favorite .htaccess links</a>, the <a href="#best-htaccess-articles">best .htaccess articles</a> on AskApache, the coolest <em><a href="#best-htaccess-articles">.htaccess experiments</a></em>, the Web's best .htaccess hacks, and update this article on the regular.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a class="IFL" href="/htaccess/htaccess.html"><img src="/wp-content/uploads/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 .htaccess&hellip; The best of the best .htaccess info I can find.</p>
<p>Originally known as the <em>Ultimate .htaccess Guide</em>, 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 <a href="#favorite-htaccess">favorite htaccess-related links and sites</a>, results from my <a href="#best-htaccess-articles">best .htaccess experiments</a>, and frequently update this article.</p>
<p>You&#8217;ve come to the right place if you are looking to acquire <strong>mad skills</strong> for using .htaccess files.</p>
<p><br class="C" /></p>
<div style="margin-left:2em;">
<p><a id="htaccess-toc" title="Htaccess - Table of Contents"></a></p>
<h2>Table of Contents</h2>
<ol class="TOC">
<li><a href="#htaccess-evolution" title="Evolution of Htaccess">Evolution of Htaccess</a></li>
<li><a href="#httpd-config-examples" title="Server Config (httpd.conf) Examples">Server Config (httpd.conf) Examples</a></li>
<li><a href="#htaccess-example-files" title="Example .htaccess Files"><strong>Example .htaccess Files</strong></a></li>
<li><a href="#htaccess-code-examples" title="Example .htaccess Code Snippets"><strong>Example .htaccess Code Snippets</strong></a></li>
<li><a href="#mod_rewrite-examples" title="Example mod_rewrite code and tricks"><strong>NEW: Advanced Mod_Rewrite Tricks</strong></a></li>
<li><a href="#best-htaccess-articles" title="Best AskApache .htaccess Articles">Best AskApache .htaccess Articles</a></li>
<li><a href="#favorite-htaccess" title="Favorite .htaccess Links">Favorite .htaccess Links</a></li>
<li><a href="#htaccess-directives-list" title="Master List of .htaccess Directives">Master List of .htaccess Directives</a></li>
<li><a href="#htaccess-modules" title="Htaccess Modules List">Htaccess Modules List</a></li>
</ol>
</div>
<p><a id="htaccess-evolution" title="Htaccess - Evolved"></a></p>
<h2>Htaccess &#8211; 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>The following .htaccess tricks, .htaccess tips, examples, samples, tutorials, tools, and plethora of &#8220;How To&#8221; htaccess articles on creating and using htaccess files will do several things for you, just like its done for me.</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><strong><dfn title="HyperText Access">.htaccess</dfn></strong> 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 is sometimes called:  &#8220;HyperText Access&#8221; because of its ability to control access of the <acronym title="World Wide Web">WWW</acronym>&#8217;s HyperText Transfer Protocol (<acronym title="HyperText Transfer Protocol">HTTP</acronym>) using Password Protection, Allow and Deny capabilities, and more.</p>
<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 &#8220;server farms&#8221; where many hundreds and thousands of web hosting customers are all put on the same Apache Server.  This type of hosting is called &#8220;virtual hosting&#8221; 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&#8217;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">
<h4>Configuration, commands and the like</h4>
<p>One of the design goals for this server was to maintain external compatibility with the NCSA 1.3 server &#8212; 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&#8217;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&#8217;s own config files (either from the <Directory> 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>Creating Htaccess Files</h4>
<p><a class="IFL" href="/wp-content/uploads/2009/01/htaccess-explorer.png"><img src="/wp-content/uploads/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 &#8220;<code>.htaccess</code>&#8221; 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&#8217;t <code>.htaccess.txt</code>, its literally just named <code>.htaccess</code>.<br class="C" /></p>
<p><a class="IFR" href="/wp-content/uploads/2009/01/viewing-htaccess-files.png"><img src="/wp-content/uploads/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&#8217;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&#8217;s an <a href='/wp-content/uploads/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&#8217;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>
<pre>
//mod_autoindex
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
&nbsp;
// 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&#8217;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&#8217;s the 3 top links (<em>official Apache Docs</em>) you will repeatedly use, bookmark/print/save them.</p>
<p><a href="/wp-content/uploads/2008/08/htaccess-up1.png"><img src="/wp-content/uploads/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 &#8212; 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&#8217;s performance, comparing to Apache&#8217;s 40% drop in performance. </p>
<p><a id="httpd-config-examples"></a></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="/wp-content/uploads/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="/wp-content/uploads/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="/wp-content/uploads/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="/wp-content/uploads/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="/wp-content/uploads/2008/08/httpd-mpmconf.in" title="Server-Pool Management (MPM specific)">httpd-mpm.conf</a>, <a href="/wp-content/uploads/2008/08/httpd-defaultconf.in" title="This configuration file reflects default settings for Apache HTTP Server">httpd-default.conf</a>, <a href="/wp-content/uploads/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="/wp-content/uploads/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="/wp-content/uploads/2008/08/httpd-vhostsconf.in" title="If you want to maintain multiple domains/hostnames on your machine">httpd-vhosts.conf</a>, <a href="/wp-content/uploads/2008/08/httpd-davconf.in" title="Distributed authoring and versioning (WebDAV)">httpd-dav.conf</a>)</p>
<hr class="C" />
<p><a id="htaccess-example-files"></a></p>
<h2>Example .htaccess Files</h2>
<p>Here are some samples and examples taken from different .htaccess files I&#8217;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
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&#46;.."
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&#46;.."
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" />
<p><a id="htaccess-code-examples"></a></p>
<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 &#8220;File Save As&#8221; 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
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" />
<p><a id="mod_rewrite-examples"></a></p>
<h2>Advanced Mod_Rewrite Examples</h2>
<p>Here are some specific examples taken mostly from my WordPress Password Protection plugin, that also does alot more than password protection as you can see from the following mod_rewrite examples.  These are a few of the mod_rewrite uses that BlogSecurity declared pushed the boundaries of Mod_Rewrite!  Some of these snippets are quite exotic and unlike anything you may have seen before, also only for those who understand them as they can kill a website pretty quick.</p>
<h4>Directory Protection</h4>
<p>Enable the DirectoryIndex Protection, preventing directory index listings and defaulting. [<a href="/htaccess/htaccess.html">Disable</a>]</p>
<pre>
Options -Indexes
DirectoryIndex index.html index.php /index.php
</pre>
<h4>Password Protect wp-login.php</h4>
<p>Requires a valid user/pass to access the login page[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-401">401</a>]</p>
<pre>
&lt;Files wp-login.php&gt;
Order Deny,Allow
Deny from All
Satisfy Any
AuthName "Protected By AskApache"
AuthUserFile /home/askapache.com/.htpasswda1
AuthType Basic
Require valid-user
&lt;/Files&gt;
</pre>
<h4>Password Protect wp-admin</h4>
<p>Requires a valid user/pass to access any non-static (css, js, images) file in this directory.[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-401">401</a>]</p>
<pre>
Options -ExecCGI -Indexes +FollowSymLinks -Includes
DirectoryIndex index.php /index.php
Order Deny,Allow
Deny from All
Satisfy Any
AuthName "Protected By AskApache"
AuthUserFile /home/askapache.com/.htpasswda1
AuthType Basic
Require valid-user
&lt;FilesMatch "\.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$"&gt;
Allow from All
&lt;/FilesMatch&gt;
&lt;FilesMatch "(async-upload)\.php$"&gt;
&lt;IfModule mod_security.c&gt;
SecFilterEngine Off
&lt;/IfModule&gt;
Allow from All
&lt;/FilesMatch&gt;
</pre>
<h4>Protect wp-content</h4>
<p>Denies any Direct request for files ending in .php with a 403 Forbidden.. May break plugins/themes [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-401">401</a>]</p>
<pre>
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /wp-content/.*$ [NC]
RewriteCond %{REQUEST_FILENAME} !^.+flexible-upload-wp25js.php$
RewriteCond %{REQUEST_FILENAME} ^.+\.(php|html|htm|txt)$
RewriteRule .* - [F,NS,L]
</pre>
<h4>Protect wp-includes</h4>
<p>Denies any Direct request for files ending in .php with a 403 Forbidden.. May break plugins/themes [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /wp-includes/.*$ [NC]
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ /wp-includes/js/.+/.+\ HTTP/ [NC]
RewriteCond %{REQUEST_FILENAME} ^.+\.php$
RewriteRule .* - [F,NS,L]
</pre>
<h4>Common Exploits</h4>
<p>Block common exploit requests with 403 Forbidden. These can help alot, may break some plugins. [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ ///.*\ HTTP/ [NC,OR]
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,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.(htpasswd|htaccess|aahtpasswd).*\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>Stop Hotlinking</h4>
<p>Denies any request for static files (images, css, etc) if referrer is not local site or empty. [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{HTTP_REFERER} !^http://www.askapache.com.*$ [NC]
RewriteRule \.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$ - [F,NS,L]
</pre>
<h4>Safe Request Methods</h4>
<p>Denies any request not using <a href="http://www.askapache.com/online-tools/request-method-scanner/">GET,PROPFIND,POST,OPTIONS,PUT,HEAD</a>[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST|PROPFIND|OPTIONS|PUT)$ [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>Forbid Proxies</h4>
<p>Denies any POST Request using a Proxy Server. Can still access site, but not comment.  See <a href="http://perishablepress.com/press/2008/04/20/how-to-block-proxy-servers-via-htaccess/">Perishable Press</a> [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:VIA}%{HTTP:FORWARDED}%{HTTP:USERAGENT_VIA}%{HTTP:X_FORWARDED_FOR}%{HTTP:PROXY_CONNECTION} !^$ [OR]
RewriteCond %{HTTP:XPROXY_CONNECTION}%{HTTP:HTTP_PC_REMOTE_ADDR}%{HTTP:HTTP_CLIENT_IP} !^$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>Real wp-comments-post.php</h4>
<p>Denies any POST attempt made to a non-existing wp-comments-post.php[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*/wp-comments-post\.php.*\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>HTTP PROTOCOL</h4>
<p>Denies any badly formed HTTP PROTOCOL in the request, 0.9, 1.0, and 1.1 only[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ .+\ HTTP/(0\.9|1\.0|1\.1) [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>SPECIFY CHARACTERS</h4>
<p>Denies any request for a url containing characters other than &#8220;a-zA-Z0-9.+/-?=&#038;&#8221;  &#8211; REALLY helps but may break your site depending on your links. [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ [a-zA-Z0-9\.\+_/\-\?\=\&amp;]+\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>BAD Content Length</h4>
<p>Denies any POST request that doesnt have a Content-Length Header[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:Content-Length} ^$
RewriteCond %{REQUEST_URI} !^/(wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>BAD Content Type</h4>
<p>Denies any POST request with a content type other than application/x-www-form-urlencoded|multipart/form-data[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:Content-Type} !^(application/x-www-form-urlencoded|multipart/form-data.*(boundary.*)?)$ [NC]
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>Missing HTTP_HOST</h4>
<p>Denies requests that dont contain a HTTP HOST Header.[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{HTTP_HOST} ^$
RewriteRule .* - [F,NS,L]
</pre>
<h4>Bogus Graphics Exploit</h4>
<p>Denies obvious exploit using bogus graphics[<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{HTTP:Content-Disposition} \.php [NC]
RewriteCond %{HTTP:Content-Type} image/.+ [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>No UserAgent, Not POST</h4>
<p>Denies POST requests by blank user-agents.  May prevent a small number of visitors from POSTING. [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP_USER_AGENT} ^-?$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>No Referer, No Comment</h4>
<p>Denies any comment attempt with a blank HTTP_REFERER field, highly indicative of spam.  May prevent some visitors from POSTING. [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*/wp-comments-post\.php.*\ HTTP/ [NC]
RewriteCond %{HTTP_REFERER} ^-?$
RewriteRule .* - [F,NS,L]
</pre>
<h4>Trackback Spam</h4>
<p>Denies obvious trackback spam.  See <a href="http://ocaoimh.ie/wordpress/more-ways-to-stop-spammers-and-unwanted-traffic/">Holy Shmoly!</a> [<a href="/htaccess/apache-status-code-headers-errordocument.html#status-403">403</a>]</p>
<pre>
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP_USER_AGENT} ^.*(opera|mozilla|firefox|msie|safari).*$ [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.+/trackback/?\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]
</pre>
<h4>Map all URIs except those corresponding to existing files to a handler</h4>
<pre>
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule . /script.php
</pre>
<h4>Map any request to a handler</h4>
<p>In the case where all URIs should be sent to the same place (including potentially requests for static content) the method to use depends on the type of the handler. For php scripts, use:<br />
For other handlers such as php scripts, use:</p>
<pre>
RewriteEngine On
RewriteCond %{REQUEST_URI} !=/script.php
RewriteRule .* /script.php
</pre>
<h4>And for CGI scripts:</h4>
<pre>
ScriptAliasMatch .* /var/www/script.cgi
</pre>
<h4>Map URIs corresponding to existing files to a handler instead</h4>
<pre>
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f
RewriteCond %{REQUEST_URI} !=/script.php
RewriteRule .* /script.php
</pre>
<p>If the existing files you wish to have handled by your script have a common set of file extensions distinct from that of the hander, you can bypass mod_rewrite and use instead mod_actions. Let&#8217;s say you want all .html and .tpl files to be dealt with by your script:</p>
<pre>
Action foo-action /script.php
AddHandler foo-action html tpl
</pre>
<h4>Deny access if var=val contains the string foo.</h4>
<pre>
RewriteCond %{QUERY_STRING} foo
RewriteRule ^/url - [F]
</pre>
<h4>Removing the Query String</h4>
<pre>
RewriteRule ^/url /url?
</pre>
<h4>Adding to the Query String</h4>
<p>Keep the existing query string using the Query String Append flag, but add var=val to the end.</p>
<pre>
RewriteRule ^/url /url?var=val [QSA]
</pre>
<h4>Rewriting For Certain Query Strings</h4>
<p>Rewrite URLs like http://askapache.com/url1?var=val to http://askapache.com/url2?var=val but don&#8217;t rewrite if val isn&#8217;t present.</p>
<pre>
RewriteCond %{QUERY_STRING} val
RewriteRule ^/url1 /url2
</pre>
<h4>Modifying the Query String</h4>
<p>Change any single instance of val in the query string to other_val when accessing /path. Note that %1 and %2 are back-references to the matched part of the regular expression in the previous RewriteCond.</p>
<pre>
RewriteCond %{QUERY_STRING} ^(.*)val(.*)$
RewriteRule /path /path?%1other_val%2
</pre>
<hr class="C" />
<p><a id="best-htaccess-articles"></a></p>
<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  &#8220;expert level&#8221; 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="/wp-content/uploads/2008/01/jail-bars-1.png" alt="Locking down your php.ini and php cgi with .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&#8217;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="/wp-content/uploads/2007/10/cookies.png" alt="Cookie Manipulation in .htaccess with RewriteRule" /></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="/wp-content/uploads/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="/wp-content/uploads/2007/11/security.png" alt="HTTP to HTTPS Redirects with mod_rewrite" /></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 &#8220;http&#8221; or &#8220;https&#8221; 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" />
<p><a id="htaccess-merging-order"></a></p>
<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>
<p>.</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>
<p><a id="favorite-htaccess"></a></p>
<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&#8217;m really into doing your own hacking to get knowledge and these links are all great resources in that respect.  I&#8217;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></p>
<p><strong>Robert Hansen</strong><br />Here&#8217;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/">&#8220;.htaccess &#8211; gzip and cache your site for faster loading and bandwidth saving.&#8221;</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&#8230; 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&#038;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&#8217;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.</p>
<p><strong>Holy Shmoly!</strong><br />A great blogger with analysis of attacks and spam.  See: <a href="http://ocaoimh.ie/wordpress/more-ways-to-stop-spammers-and-unwanted-traffic/">More ways to stop spammers and unwanted traffic</a>.</p>
<p><strong>Apache Week</strong><br />A partnership with Red Hat back in the 90&#8217;s that produced some <a href="http://www.apacheweek.com/features/userauth">excellent documentation</a>.</p>
<p><strong>Corz</strong><br />Here&#8217;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&#8217;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>.</a></p>
<hr class="C" />
<p><a id="htaccess-directives-list"></a></p>
<h2>Htaccess Directives</h2>
<p class="anote">This is an AskApache.com exclusive <em>you won&#8217;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" />
<p><a id="htaccess-modules"></a></p>
<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" />
<p><span id="more-23"></span></p>
<p><a href="http://www.askapache.com/htaccess/htaccess.html">Ultimate Htaccess Tutorial for .htaccess files</a> originally appeared on AskApache.</p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/htaccess/htaccess.html/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		</item>
	</channel>
</rss>
