FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home  »  Htaccess  »  .htaccess Examples: Cookies, Variables, Custom Headers

by 13 comments

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 on DreamHost. Enjoy!



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/$ /$1.html [R=301,L]

Or a lower quality alternative

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^[^.]+.html/$
RewriteRule ^(.*).html.*$ /$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"

Tags

March 29th, 2008

Comments Welcome

  • http://mrapache.blogspot.com htaccess cookie monster

    Wow awesome cookie examples!

  • Mithilesh

    Yep very nice Cookie Manipulation. Hope you will write more topics like URL Hotlink Protections and Vertiual Directory Creations

  • David

    I was looking for .htaccess examples like these... thank you!

  • Tom

    Is it possible to set the environment to the value of the URI in the current url?
    In other words save the URI until the next visitor arrives.
    Using htaccess...

  • Jairo Gelvez

    Excelentes ejemplos, me ha quedado muy claro el manejo de las cookies.

    Excellent examples, I have been very clear about the handling of cookies.

  • jorge

    In the example: Redirect If Cookie Not Set, I think you need space, like:

    RewriteCond %{HTTP_COOKIE} !^.*cookie-name.*$ [NC]
  • Ezra

    Thank you so much! I been searching for ages to figure out how to rewrite based on the value of a cookie.

  • Paul O-H

    httpd-2.0.53
    Running on port 8040
    When connected, how do I prevent the port number from displaying in the URL?
    e.g.
    Link is http://site:8040
    Want URL to display http://site

  • Matatat

    Good article here - I have a tricky one that I cannot find the answer to so posting here to see if anyone can help.

    I need to create a rewrite condition to detect if a cookie is there. If the cookie is there and the value is not XX then the rewrute rule should apply.

    I have got the existance check for the cookie which works but when I add the conditional check for if it is there and value is XX the condition fails :(

    Any ideas - the first one works but with the introduction of the second both fail? The scenario will be that some users may have the cookie and some may not. For those that have if the value is set to XX i want to rewrite.

    My rule is as below:

    #    if CO mycookie exists and the value != 'XX' then do not redirect
    RewriteCond %{HTTP_COOKIE} !^.*mycookie.*$ [NC]
    RewriteCond %{HTTP_COOKIE} mycookie=XX [NC]
  • http://www.askapache.com/ AskApache

    @Matatat
    This is one I myself use, pay attention to the beginning and ending wildcards in the rewritecond for HTTP_COOKIE.

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /(.*) HTTP/ [NC]
    RewriteCond %{HTTP_COOKIE} !^.*cookiename=thecookievaluegoeshere.*$ [NC]
    RewriteRule . https://www.askapache.com/wp-login.php?redirect_to=%1 [R=302,L]
  • http://www.r3now.com Bill Wood

    Can you do a short tutorial on manipulating cookie values?

    I have your Wordpress 404 plugin, other than some tweaks I've made it is really great. I have learned a TON from your site about settings in the .htaccess file and have mine massively customized for performance. Between that and caching I'm generally getting pretty good performance considering the amount of content and plugins I serve.

    One thing that has plagued me for a long time is cookie size...

    I am STUCK with my single domain that sets cookies for everything. What I am looking for is some key info on how to set the cookie size to its smallest possible size for all images, .js files, etc.

    Can you do a short tutorial on manipulating cookie values? That would help a LOT!

  • http://www.thinkcreative.com Bob

    Could you provide me an example of deleting or removing a cookie if the user requests a specific page?

    For example, if the user navigates to /user/logout... do you just set the expiration date/time to 0000?

  • http://www.daretoprofitonline.com/ Jesse Josserand

    I have a site that is constantly getting hacked. I've implemented directory level security on my admin directory where there is a vulnerable php login file for normal website admin access which is how I found the hacker(s) were getting in. That resolved it for about a month. However, they've found another way and I have not been able to determine the entry point. What log(s) can I find that info in, as well as the IP(s) used and how can they be blocked?


Related Articles


My Online Tools
Popular Articles


Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman









[hide]

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

+Askapache | askapache

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service

↑ TOPMain