[Apache] Don’t use .htaccess files

Apache has a very convenient feature: loading setting files from a webapp directories on the fly. These .htaccess files allow you to tweak the server’s behavior without access to the standard setting files. That a killer feature in a shared hosting environment but beside this particular case, you shouldn’t use it. Why ? Because there are serious drawback !

Performance hit

When AllowOverride all is used Apache will look for .htaccess files in every directory on the path of each served files. That pretty bad but it gets even worse: for each request the content of every .htaccess is read again. As you can imagine that a serious performance hit.

Security concern

Not all parameters can be overridden into .htaccess files, but there is already a lot you can do with a little imagination. For example an attacker could use an application vulnerability to modify a .htaccess in order to add a new file handler, so that .jpeg files are now processed by PHP.

By doing this he can now bypass most webapp upload ‘protection’ mechanism. You can sure the next .jpeg upload will not be a picture of a busty girl but something way more nasty, like a C99 shell.

Maintainability concern

Sometimes a customer will complain that a particular rewrite rule or a specific php setting doesn’t behave like expected. That weird, because you are sure you made ​​the appropriate changes. Surprise surprise, the behavior is altered into a .htaccess file, hidden somewhere in a 5-depth directory structure.

Integrate htaccess content into standard setting files

Many applications come with their own .htaccess. This file generally contain all the required rewrites rules to ensure their proper functioning. It can be very annoying to adapt its content into a standard apache setting file, because the syntax isn’t completely the same.

Fortunately there is a small tip that will save you a lot of trouble and time: you can just copy the rewrites rules into your main Directory block and then add a RewriteBase / line into it.

Split a file into multiple files

Let say you have a file with multiple sections, delimited by the character sequence -|, and you need to create multiple files, one for each section. How you do that ?

Basically you can use three tools for the job.

Use csplit

Csplit is a very useful and not well know utility, present into coreutils package.

csplit --quiet --prefix=outfile infile.txt  "/-|/+1" "{*}"

Use awk

awk '{print $0 " -|"> "output" NR}' RS='-\\|' infile.txt

Use bash/perl/python

Here i give you the bash one-liner version, but you can also use perl, python, ruby or any other scripting language:

cat infile.txt | ( I=0; echo -n "" > output0; while read line; do echo $line >> output$I; if [ "$line" == '-|' ]; then I=$[I+1]; echo -n "" > output$I; fi; done )