Search code examples
regexapachemod-rewritehttp-redirectmod-alias

Redirect Rule to match certain keywords but not others


I am trying to write a RedirectMatch (apache) that matches some keywords except one.

...
RewriteEngine  on
RedirectMatch   ^/(banners|documents|images|static)/(.*)$ http://sb.amazonaws.com/$1/$2
RewriteRule     ^(.*)/(vrf[0-9]+)/(.*).(js|css)$  $1/$3.$4 [PT]

I came up with this RedirectMatch rule that redirects all of the urls that contain banners, documents etc. to the aws domain.

Now, I want to prevent urls that contain temp to go to the aws domain. For that I added !temp

RedirectMatch   ^/(!temp|banners|documents|images|static)/(.*)$ http://sb.amazonaws.com/$1/$2

This disallows urls like mysite.com/temp/a.jpg to go to AWS (but complains about an infinite loop) but does NOT prevent mysite.com/images/temp/a.jpg from being redirected. What should be the correct regex for this rule?

[EDIT]

  • mysite.com/images/foo/a.jpg should go to AWS
  • mysite.com/images/foo/temp/a.jpg should NOT go to AWS
  • mysite.com/temp/a.jpg should NOT got to AWS

[EDIT2] This brought me close to what I was looking for

RewriteEngine  on
RewriteRule ^(images/groups/temp)/(.*)$ $1/$2 [PT]
RewriteRule ^(banners|documents|images|static)/(.*)$ http://sb.amazonaws.com/$1/$2
RewriteRule ^(.*)/(vrf[0-9]+)/(.*).(js|css)$  $1/$3.$4 [PT]

Solution

  • Don't mix RedirectMatch with RewriteRule. Use a RewriteCond to add exceptions:

    RewriteEngine  on
    
    RewriteCond %{REQUEST_URI} !^/images/groups/temp/ [NC]
    RewriteRule ^(banners|documents|images|static)/(.*)$ http://sb.amazonaws.com/$1/$2 [L,NC,R]
    
    RewriteRule ^(.*)/(vrf[0-9]+)/(.*).(js|css)$  $1/$3.$4 [PT]