Tuesday, January 24, 2012

Htaccess Rewrites – Rewrite Tricks and Tips

SkyHi @ Tuesday, January 24, 2012
Contents
  1. Htaccess rewrites TOC
  2. .htaccess rewrite examples should begin with:
  3. Require the www
  4. Loop Stopping Code
  5. Cache-Friendly File Names
  6. SEO friendly link for non-flash browsers
  7. Removing the Query_String
  8. Sending requests to a php script
  9. Setting the language variable based on Client
  10. Deny Access To Everyone Except PHP fopen
  11. Deny access to anything in a subfolder except php fopen
  12. Require no www
  13. Check for a key in QUERY_STRING
  14. Removes the QUERY_STRING from the URL
  15. Fix for infinite loops
  16. External Redirect .php files to .html files (SEO friendly)
  17. Internal Redirect .php files to .html files (SEO friendly)
  18. block access to files during certain hours of the day
  19. Rewrite underscores to hyphens for SEO URL
  20. Require the www without hardcoding
  21. Require no subdomain
  22. Require no subdomain
  23. Redirecting WordPress Feeds to Feedburner
  24. Only allow GET and PUT Request Methods
  25. Prevent Files image/file hotlinking and bandwidth stealing
  26. Stop browser prefetching
  27. Directives
  28. htaccess Guide Sections
Htaccess Rewrites are enabled by using the Apache module mod_rewrite, which is one of the most powerful Apache modules and features availale. Htaccess Rewrites through mod_rewrite provide the special ability to Rewrite requests internally as well as Redirect request externally.
When the url in your browser's location bar stays the same for a request it is an internal rewrite, when the url changes an external redirection is taking place. This is one of the first, and one of the biggest mental-blocks people have when learning about mod_rewrite... But I have a secret weapon for you to use, a new discovery from years of research that makes learning mod_rewrite drastically quicker and easier. It truly does or I wouldn't be saying so in the introduction of this article.
Despite the tons of examples and docs, mod_rewrite is voodoo. Damned cool voodoo, but still voodoo.
-- Brian Moore
Note: After years of fighting to learn my way through rewriting urls with mod_rewrite, I finally had a breakthrough and found a way to outsmart the difficulty of mod_rewrite that I just couldn't seem to master. The Mod_Rewrite RewriteCond/RewriteRule Variable Value Cheatsheet is the one-of-a-kind tool that changed the game for me and made mod_rewriting no-harder than anything else.
So keep that mod_rewrite reference bookmarked and you will be able to figure out any RewriteRule or RewriteCond, an amazing feat considering it took me a LONG time to figure this stuff out on my own. But that was before the craziness, one of the most challenging and productive .htaccess experiments I've done... An experiment so ILL it's sick like a diamond disease on your wrist! $$$. That mod_rewrite experiment/tutorial was the culmination of many different advanced mod_rewrite experiments I had done in the past and included most of my very best .htaccess tricks. With the cheatsheet it's no longer Voodoo.. Its just what you do. Now lets dig in!

Htaccess rewrites TOC ^


If you really want to take a look, check out the mod_rewrite.c and mod_rewrite.h files.
Be aware that mod_rewrite (RewriteRule, RewriteBase, and RewriteCond) code is executed for each and every HTTP request that accesses a file in or below the directory where the code resides, so it's always good to limit the code to certain circumstances if readily identifiable.
For example, to limit the next 5 RewriteRules to only be applied to .html and .php files, you can use the following code, which tests if the url does not end in .html or .php and if it doesn't, it will skip the next 5 RewriteRules.

RewriteRule !\.(html|php)$ - [S=5]
RewriteRule ^.*-(vf12|vf13|vf5|vf35|vf1|vf10|vf33|vf8).+$ - [S=1]

.htaccess rewrite examples should begin with: ^

Options +FollowSymLinks
 
RewriteEngine On
RewriteBase /

Require the www ^

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule ^(.*)$ http://www.askapache.com/$1 [R=301,L]

Loop Stopping Code ^

Sometimes your rewrites cause infinite loops, stop it with one of these rewrite code snippets.
RewriteCond %{REQUEST_URI} ^/(stats/|missing\.html|failed_auth\.html|error/).* [NC]
RewriteRule .* - [L]
 
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

Cache-Friendly File Names ^

This is probably my favorite, and I use it on every site I work on. It allows me to update my javascript and css files in my visitors cache's simply by naming them differently in the html, on the server they stay the same name. This rewrites all files for /zap/j/anything-anynumber.js to /zap/j/anything.js and /zap/c/anything-anynumber.css to /zap/c/anything.css
RewriteRule ^zap/(j|c)/([a-z]+)-([0-9]+)\.(js|css)$ /zap/$1/$2.$4 [L]

SEO friendly link for non-flash browsers ^

When you use flash on your site and you properly supply a link to download flash that shows up for non-flash aware browsers, it is nice to use a shortcut to keep your code clean and your external links to a minimum. This code allows me to link to site.com/getflash/ for non-flash aware browsers.
RewriteRule ^getflash/?$ http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash [NC,L,R=307]

Removing the Query_String ^

On many sites, the page will be displayed for both page.html and page.html?anything=anything, which hurts your SEO with duplicate content. An easy way to fix this issue is to redirect external requests containing a query string to the same uri without the query_string.
RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/
RewriteCond %{QUERY_STRING} !^$
RewriteRule .* http://www.askapache.com%{REQUEST_URI}? [R=301,L]

Sending requests to a php script ^

This .htaccess rewrite example invisibly rewrites requests for all Adobe pdf files to be handled by /cgi-bin/pdf-script.php
RewriteRule ^(.+)\.pdf$  /cgi-bin/pdf-script.php?file=$1.pdf [L,NC,QSA]

Setting the language variable based on Client ^

For sites using multiviews or with multiple language capabilities, it is nice to be able to send the correct language automatically based on the clients preferred language.
RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
RewriteRule ^(.*)$ - [env=prefer-language:%1]

Deny Access To Everyone Except PHP fopen ^

This allows access to all files by php fopen, but denies anyone else.
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^.+$ [NC]
RewriteRule .* - [F,L]
If you are looking for ways to block or deny specific requests/visitors, then you should definately read Blacklist with mod_rewrite. I give it a 10/10

Deny access to anything in a subfolder except php fopen ^

This can be very handy if you want to serve media files or special downloads but only through a php proxy script.
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+)/.*\ HTTP [NC]
RewriteRule .* - [F,L]

Require no www ^

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^askapache\.com$ [NC]
RewriteRule ^(.*)$ http://askapache.com/$1 [R=301,L]

Check for a key in QUERY_STRING ^

Uses a RewriteCond Directive to check QUERY_STRING for passkey, if it doesn't find it it redirects all requests for anything in the /logged-in/ directory to the /login.php script.
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} !passkey
RewriteRule ^/logged-in/(.*)$ /login.php [L]

Removes the QUERY_STRING from the URL ^

If the QUERY_STRING has any value at all besides blank than the?at the end of /login.php? tells mod_rewrite to remove the QUERY_STRING from login.php and redirect.
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} .
RewriteRule ^login.php /login.php? [L]

Fix for infinite loops ^

An error message related to this isRequest exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.or you may seeRequest exceeded the limit,probable configuration error,Use 'LogLevel debug' to get a backtrace, orUse 'LimitInternalRecursion' to increase the limit if necessary
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

External Redirect .php files to .html files (SEO friendly) ^

RewriteRule ^(.*)\.php$ /$1.html [R=301,L]

Internal Redirect .php files to .html files (SEO friendly) ^

Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php
RewriteRule ^(.*)\.html$ $1.php [R=301,L]

block access to files during certain hours of the day ^

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# If the hour is 16 (4 PM) Then deny all access
RewriteCond %{TIME_HOUR} ^16$
RewriteRule ^.*$ - [F,L]

Rewrite underscores to hyphens for SEO URL ^

Converts all underscores "_" in urls to hyphens "-" for SEO benefits... See the full article for more info.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
 
RewriteRule !\.(html|php)$ - [S=4]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]
 
RewriteCond %{ENV:uscor} ^Yes$
RewriteRule (.*) http://d.com/$1 [R=301,L]

Require the www without hardcoding ^

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
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]

Require no subdomain ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

Require no subdomain ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Redirecting WordPress Feeds to Feedburner ^

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/feed\.gif$
RewriteRule .* - [L]
 
RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]
RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Only allow GET and PUT Request Methods ^

Article: Request Methods
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} !^(GET|PUT)
RewriteRule .* - [F]

Prevent Files image/file hotlinking and bandwidth stealing ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?askapache.com/.*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

Stop browser prefetching ^

RewriteEngine On
SetEnvIfNoCase X-Forwarded-For .+ proxy=yes
SetEnvIfNoCase X-moz prefetch no_access=yes
 
# block pre-fetch requests with X-moz headers
RewriteCond %{ENV:no_access} yes
RewriteRule .* - [F,L]
This module uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule, to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests, of server variables, environment variables, HTTP headers, or time stamps. Even external database lookups in various formats can be used to achieve highly granular URL matching.
This module operates on the full URLs (including the path-info part) both in per-server context (httpd.conf) and per-directory context (.htaccess) and can generate query-string parts on result. The rewritten result can lead to internal sub-processing, external request redirection or even to an internal proxy throughput.
Further details, discussion, and examples, are provided in the detailed mod_rewrite documentation.

Directives ^

If you aren't already comfortable using mod_rewrite then I recommend this excellent mod_rewrite guide by one of my favorite mod_rewrite gurus that I've met.

htaccess Guide Sections ^


REFERENCES
http://www.askapache.com/htaccess/modrewrite-tips-tricks.html

Monday, January 23, 2012

3 Ways to Serve PDF Files using Htaccess Cookies, Headers, Rewrites

SkyHi @ Monday, January 23, 2012
FYI, using the Mod_Rewrite Variables Cheatsheet makes this example, and all advanced .htaccess code easier to understand. This demo lets you set a cookie with 1 of 3 values, then you just request the pdf file with a normal link click and get 1 of 3 different responses. This is accomplished with a nice bit of .htaccesscode.

As I explain the htaccess code that achieves this, keep in mind this is merely one simple application for this code. It's much more advanced than your basic htaccess trick, notice how this htaccess acts like a php script, very unusual.. I really wanted to share this trick after I created it for one of my clients because this is the tip of the iceberg. Another use would be to display an alternate style sheet depending on a users theme preference. The coolest thing is that it uses multiple advanced .htaccess ideas. This code uses mod_headers to set the Content-Disposition header for forcing a download and uses mod_rewrite to: Send different Content-Type headers, Check the value of a cookie, Set environment variables for use later by mod_headers header directive
Set PDF Viewing Mode - Make a selection, then click the view pdf button.
InlineDownloadSave AsView PDF using selected mode »

What's Going On ^

There are 3 different ways for a server to send a pdf file in response to a request for one. This causes 3 different ways to open/view the pdf file in the clients browser.
  1. The browser display's a "Save File As" dialog, allowing you to save the file or open.
  2. The browser opens the pdf file "Inline", opening the pdf file in the browser like a web page.
  3. The browser "Downloads" the pdf file automatically as an "Attachment" and then causes an external pdf reader program like adobe reader to open the file.
Some people prefer to have the option of saving the file to view later, some prefer opening it with an external program, and some just like the pdf file to load right in the browser... The point is that by using .htaccess, we can let them choose any of the 3 methods and save their preference for all further pdf files requested from our site by that user.

How It Works ^

When you click on one of the 3 demo buttons above, "Inline", "Save As", or "Download", a cookie named askapache_pdf is saved in your browser using the javascript below, with the value being set to which button you clicked. Then when you request the pdf file the .htaccess code below uses mod_rewrite to read the value of the askapache_pdf cookie, and depending on which was your preference it will send alternate HTTP Headers that control how your browser handles the file.

Unique HTTP Headers Returned ^

When it comes down to it, the following information is the 3 modes. Notice each one is different, because these headers are the only thing controlling how your browser handles the file.

Save As Mode (askapache_pdf=s) ^

Content-Disposition: attachment
Content-Type: application/pdf

Inline Mode (askapache_pdf=i) ^

Content-Type: application/pdf

Download Mode (askapache_pdf=a) ^

Content-Type: application/octet-stream

Htaccess Demo File ^

For the demo I created the folder /storage/pdf/ and this is the .htaccess file at /storage/pdf/.htaccess
The default Content-Type for .pdf files. This will make .pdf files default Content-Type header have the value 'application/pdf' - but the default can be overridden by using RewriteRule with the [T='different/type']
AddType application/pdf .pdf
Turn on the rewrite engine if its already on you dont need this
RewriteEngine On
Skip RewriteRules if not .pdf request, like autoindexing. The next [2] RewriteRule directives are specific for .pdf files so if the filename requested does not end in .pdf then the [S=2] instructs the next 2 RewriteRule directives to be completely skipped.
RewriteRule !.*\.pdf$ - [S=2]
The first RewriteCond checks to see if the askapache_pdf cookie is NOT set. The second RewriteCond checks to see if the askapche_pdf cookie has the value of s, which is the value corresponding to someone clicking the "Save As" button.
The [NC,OR] flag means that if the cookie askapache_pdf does not exist, OR (next cond) if the askapache_pdf cookie does exist and is set to 's' then process the RewriteRule. If neither cond is true the rewriterule is skipped.
If one of the RewriteCond is true, then the RewriteRule is processed. The RewriteRule applies to any/all requests (.*) but doesn't rewrite anything (-) This RewriteRule sets an Apache environment variable ASKAPACHE_PDFS to have the value of 1 if either rewritecond is true. The variable can be checked by any directives following the rewriterule in the whole htaccess file. The ASKAPACHE_PDFS ends in S because if this variable exists then it means the users preference is 'Save As'
Notice that if the user requested the pdf file without selecting a preference i.e. no cookie exists, then the ASKAPACHE_PDFS variable is still set. This just lets us pick the default preference for them, in this example the default is 'Save As'
RewriteCond %{HTTP_COOKIE} !^.*askapache_pdf.*$ [NC,OR]
RewriteCond %{HTTP_COOKIE} ^.*askapache_pdf=s.*$ [NC]
RewriteRule .* - [E=ASKAPACHE_PDFS:1]
The RewriteCond checks the askapache_pdf cookie for the value 'a' which 'a' represents 'Download'
If the cookies value is 'a' then the RewriteRule overrides the default Content-Type from 'application/pdf' set with AddType earlier, to 'application/octet-stream', which is a special content-type that tells the browser that the file cannot be loaded by the browser 'Inline', but must be saved which will be opened by an external viewer depending on browser configuration and plugins.
RewriteCond %{HTTP_COOKIE} ^.*askapache_pdf=a.*$
RewriteRule .* - [T=application/octet-stream]
This is superfly. If the cookie/users-preference was 'Save As' (s) then the RewriteRule above the last one set the environment variable ASKAPACHE_PDFS to have the value 1. The Header directive here is ONLY processed in that variable ASKAPACHE_PDFS exists. That is what the end 'env=ASKAPACHE_PDFS' does, it is the condition that must be met or the Header directive is skipped. If the ASKAPACHE_PDFS environment variable set by RewriteRule does exist then the header directive adds the header 'Content-Disposition: attachment' to the normal Response Headers. The 'Content-Disposition: attachment' header instructs your browser to present you with the 'Save As' dialog box allowing you to choose whether you want to save or open.
Header set Content-Disposition "attachment" env=ASKAPACHE_PDFS

Javascript used by Demo ^

The best place for javascript is quirksmode, here is a definitive article on setting, reading, parsing, etc.. COOKIES.
Note, I now prefer using jQuery over my AAJS javascript library. Also, the whole using cookies aspect is just to highlight some advanced htaccess, you can accomplish this much easier without javascript or cookies.
if(!gi('pdfr'))return;
var pdfr=gi('pdfr');
var cval=getCookie('askapache_pdf');
 
if(cval=='i'){pdfr.innerHTML='Currently set to "Inline".';}
else if(cval=='a'){pdfr.innerHTML='Currently set to "Download" mode.';}
else if(cval=='s'){pdfr.innerHTML='Currently set to "Save As" mode.';}
 
addMyEvent(gi('pdfi'),"mousedown",function(){
  setCookie("askapache_pdf", "i", "", "/", "www.askapache.com"); gi('pdfr').innerHTML = 'Changed mode to "Inline".'; return false; });
addMyEvent(gi('pdfa'),"mousedown",function(){
  setCookie("askapache_pdf", "a", "", "/", "www.askapache.com"); gi('pdfr').innerHTML = 'Changed mode to "Download".'; return false; });
addMyEvent(gi('pdfs'),"mousedown",function(){
  setCookie("askapache_pdf", "s", "", "/", "www.askapache.com"); gi('pdfr').innerHTML = 'Changed mode to "Save As".'; return false; });

Alternative Method - No Cookies + PHP ^

This is what I came up with first for my client, and then while programming the php I noticed.. Hey! I think I can do the same thing using .htaccess, which would save me on cpu/memory/potential security/etc.. but this works great too. Though you will need to hack the code to get it working probably..
Note that the .htaccess rewrite code I used here used FILENAME-i.pdf or FILENAME-s.pdf to pass the preference to the pdf-dl.php script, it also worked for FILENAME.pdf?i=i

pdf-dl.php ^

Alternate Method .htaccess ^

Deny direct request to pdf-dl.php file
RewriteCond %{THE_REQUEST} ^.*pdf-dl\.php.*$ [NC]
RewriteRule .* - [F]
Handle PDF files named anything-i.pdf as inline
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]*)-i\.pdf$  /cgi-bin/pdf-dl.php?i=i&file=%{DOCUMENT_ROOT}/storage/pdf/$1.pdf [L,NC,QSA,S=1]
Handle PDF files without -i.pdf as attachments
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]*)\.pdf$  /cgi-bin/pdf-dl.php?file=%{DOCUMENT_ROOT}/storage/pdf/$1.pdf [L,NC,QSA]



REFERENCES
http://www.askapache.com/htaccess/pdf-cookies-headers-rewrites.html

.htaccess Examples: Cookies, Variables, Custom Headers

SkyHi @ Monday, January 23, 2012
Cookie Manipulation in .htaccess with RewriteRuleGot some fresh .htaccess and mod_rewrite code for you! Check out the Cookie Manipulation and Tests using mod_rewrite! Also see how to set environment variables and then use them to send custom Headers (like content-language) and Rewrite based on them. And a couple Mod_Security .htaccess examples, for those smart enough to run onDreamHostEnjoy!

Mod_Rewrite .htaccess Examples ^

Redirect Request ending in .html/ to .html ^

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)\.html/\ HTTP/
RewriteRule ^(.+)\.html/$ http://www.askapache.com/$1.html [R=301,L]

Or a lower quality alternative ^

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^[^\.]+\.html/$
RewriteRule ^(.*)\.html.*$ http://www.askapache.com/$1.html [R=301,L]

Redirect All Feeds to Feedburner's MyBrand ^

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(feed|wp-atom|wp-feed|wp-rss|wp-rdf|wp-commentsrss)(.*)\ HTTP/ [NC,OR]
RewriteCond %{QUERY_STRING} ^feed [NC]
RewriteCond %{HTTP_USER_AGENT} !^(FeedBurner|FeedValidator|talkr) [NC]
RewriteRule .* http://feeds.askapache.com/apache/htaccess? [R=307,L]

Cookie Manipulation and Tests with mod_rewrite ^

Set a Cookie based on Requested directory ^

This code sends the Set-Cookie header to create a cookie on the client with the value of a matching item in 2nd parantheses.
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)(de|es|fr|it|ja|ru|en)/$ - [co=lang:$2:.askapache.com:7200:/]

Get Cookie Value ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} lang=([^;]+) [NC]
RewriteRule ^(.*)$ /$1?cookie-value=%1 [R,QSA,L]

Rewrite Based on Cookie Value ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} lang=([^;]+) [NC]
RewriteRule ^(.*)$ /$1?lang=%1 [NC,L,QSA]

Redirect If Cookie Not Set ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !^.*cookie-name.*$ [NC]
RewriteRule .* /login-error/set-cookie-first.cgi [NC,L]

Setting Environment Variables ^

Set lang var to Accept-Language Header ^

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
RewriteRule ^(.*)$ - [env=lang:%1]

Set lang var to URI ^

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)/(de|es|fr|it|ja|ru|en)/\ HTTP/ [NC]
RewriteRule ^(.*)$ - [env=lang:%2]

Using the Environment Variable ^

Send Content-Language Header based on environment variable ^

Header set Content-Language "%{lang}e" env=lang

Set a Cookie with env variable value only if has value ^

Header set Set-Cookie "language=%{lang}e; path=/;" env=lang

Echo all Headers back! ^

Header echo ^.*

Mod_Security .htaccess Examples ^

ModSecurity is an open source intrusion detection and prevention engine for web applications (or a web application firewall). Operating as an Apache Web server module or standalone, the purpose of ModSecurity is to increase web application security, protecting web applications from known and unknown attacks.

Turn OFF mod_security ^


SecFilterEngine Off
SecFilterScanPOST Off

Reject Requests with Status 500 ^


# Reject requests with status 500
SecFilterDefaultAction "deny,log,status:500"



REFERENCES
http://www.askapache.com/htaccess/htaccess-fresh.html