mod_rewrite to edit cookies conditionally

15,867

You can Get/Detect/check for existance of cookie through RewriteCond %{HTTP_COOKIE}

Set Cookie value with the RewriteRule flag cookie|CO which has this syntax: [CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly]

An example with them both together:

RewriteCond %{HTTP_COOKIE} cookiekey=cookievalue [NC]
RewriteRule ^(.*)$ /$1 [L,CO=cookiekey:NewCookieValue:mydomain.com:86400:/]

In the example above the redirection will only happen if cookiekey has a value of cookievalue. You can also use regex in the cookievalue RewriteCond if you desire.

More examples (read user comments as well): http://www.askapache.com/htaccess/htaccess-fresh.html#Cookie_Manipulation_Tests_mod_rewrite

Share:
15,867

Related videos on Youtube

PinkElephantsOnParade
Author by

PinkElephantsOnParade

Updated on September 18, 2022

Comments

  • PinkElephantsOnParade
    PinkElephantsOnParade 3 months

    Is it possible to use mod_rewrite to modify values in cookies based upon a condition? I am completely new to HTTP, but I have tried a thing or two. The only regex I know is Perl-style, I hope it is okay.

    RewriteRule s/.[0-9][0-9][0-9]/COOKIE=MSFNODE/g;
    
    1. MSFNODE is a value in my cookie.
    2. The thing I want to run my regex on is SESSIONID (also in my cookie). I'm not sure how to choose that as a target.
    3. As the regex shows, I want to replace .[0-9][0-9][0-9] with my cookie value called MSFNODE, but only if MSFNODE exists!

    Is COOKIE=MSFNODE the right way to do this? Also, I only want this to happen if MSFNODE exists — as it is now, will it just pass on through and not follow the rewrite rule if MSFNODE doesn't exist?

    I feel like even my most basic regex is flawed here.

    • joosthoek
      joosthoek over 10 years
      You could probably do this with mod_rewrite, but honestly, I suspect there are more appropriate tools for the job. It might help if you told us just what you want to accomplish with this.
    • DocRoot
      DocRoot over 6 years
      @IlmariKaronen You can manually set the Set-Cookie header using mod_headers, but if you need to set this "conditionally", your options are limited unless you are on Apache 2.4 (expressions). mod_rewrite handles this just fine on all versions of Apache.
  • DocRoot
    DocRoot about 6 years
    Looks like a typo... it should be CO= (not CO:) in your example (as you have stated in the syntax just above it).