Rewrite img and link paths with htaccess and serve the file from rewritten path?

Posted by frequent on Pro Webmasters See other posts from Pro Webmasters or by frequent
Published on 2012-03-15T09:03:51Z Indexed on 2012/04/14 23:48 UTC
Read the original article Hit count: 245

Filed under:
|

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]   
 </IfModule>

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.

EDIT:
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]
 </IfModule>

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

Thanks for help!

© Pro Webmasters or respective owner

Related posts about htaccess

Related posts about mod-rewrite