Wednesday, January 19, 2011

mod_rewrite add and switch directory

How to change the url pattern with mod_rewrite first from

domain.de/images/myfile.jpg

to

domain.de/directory/images/myfile.jpg

and then finally to

domain.de/images/directory/myfile.jpg

My rules so far

RewriteCond %{HTTP_HOST} ^(www\.)?domain\.de$
RewriteCond %{REQUEST_URI} !^\/directory
RewriteRule ^(.*)$                                              directory/$1 [NC]


RewriteCond %{REQUEST_URI} ^\/directory\/images
RewriteRule ^\/directory\/images\/(.*)$                       images/directory/$1 [qsappend,L]

The first part is working but the exchange of directory fails

  • After processing the second rewrite rule the first rewrite rule gets into an endless loop. To interrupt I had to change the first rule to check if "directory" is part of the url at all, like this:

    RewriteCond %{HTTP_HOST} ^(www\.)?domain\.de$
    RewriteCond %{REQUEST_URI} !\/directory\/
    RewriteRule ^(.*)$                                              directory/$1 [NC]
    
  • Have you tried:

    RewriteCond %{HTTP_HOST} ^(www\.)?domain\.de$
    RewriteCond %{REQUEST_URI} !^/directory/
    RewriteRule ^(.*)$                                              directory/$1 [NC]
    

    Note the RHS is !^/directory/, with the anchoring ^.

    (Is the HTTP_HOST check really necessary? Can't you put this in the VirtualHost section for domain.de?)

    The second rewrite need only be:

    RewriteRule ^/(directory)/(images)/(.*) /$2/$1/$3 [QSA,L]
    

    I don't think you need the RewriteCond in this clause; if the URI doesn't begin with /directory/images then the rule won't match, so the RewriteCond is redundant.

0 comments:

Post a Comment