I have a static mockup page, which I want to "customize" by switching a variable used in image-src and link-href attributes.

Paths will look like this:

<img src="/some/where/VARIABLE/img/1.jpg" alt="" />
<link rel="some" href="/some/where/VARIABLE/stuff/foo.bar" />

I'm setting a cookie with the VARIABLE value on the preceding page and now want to modfiy the paths accordingly by replacing VARIABLE with the cookie value.

I'm a htaccess newbie. This is what I have (doesn't work):

 <IfModule mod_rewrite.c>
    # get cookie value cookie
    RewriteCond %{HTTP_COOKIE} client=([^;]*)
    # rewrite/redirect to correct file
    RewriteRule  ^/VARIABLE/(.+)$  /%1/$1 [L]   

So I thought my first line gets the cookie value and stores this in %1. And on the second line I'm filtering VARIABLE, replace it with the cookie value and whatever comes after VARIABLE in $1.

Thanks for sheeding some light on what I'm doing, doing wrong and if I can do this at all using htaccess.

I'm sort of halfway through, but it's still not working... Mabye someone can apply the finishing touches:

 <IfModule mod_rewrite.c>
    # check for client cookie   
    RewriteCond %{HTTP_COOKIE} (?:^|;\s*)client=([^;]*)
    # check if an image was requested   
    RewriteCond %{REQUEST_FILENAME} \.(jpe?g|gif|bmp|png)$
    # exclude these folders
    RewriteCond %{REQUEST_URI} !some/members/logos  

    # grab everything before the variable folder and everything afterwards
    # replace this with first bracket/cookie_value/second bracket
    RewriteRule (^.+)/VARIABLE/(.+)$ $1/%1/$2 [L]

Still can't get it to work, but I think this is the correct way of doing it.


1 Answer 1


Solution: (after much meddling...)

<IfModule mod_rewrite.c>
   # exclude these folders
   RewriteCond %{REQUEST_URI} !/some/members/logos  
   # check for client cookie        
   RewriteCond %{HTTP_COOKIE} client=([^;]*) [NC]       
   # replace variable with cookie value
   RewriteRule ^(.+)/variabel/(.+\.(jpe?g|gif|bmp|png))$ $1/%1/$2 [L]

The tricky part, which took forever to solve is to make sure your cookie has a trailing semi-colon... I had my cookie set like this:

   document.cookie = "client=value"

which did not work at all. After changing to this:

   document.cookie = "client="+escape("value")+";"

it worked. Semi-colon... Maybe this save somebody half a day of searching :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.