0

I'm trying to redirect newsletter URLs from my local server to an Amazon S3 bucket.

So I want to redirect from:

https://mysite.com/assets/img/newsletter/Jan12_Newsletter.html

to:

https://s3.amazonaws.com/mybucket/newsletters/legacy/Jan12_Newsletter.html

Here's the first part of my rule:

RewriteEngine On
RewriteBase /

# Is it in the newsletters directory
RewriteCond %{REQUEST_URI} ^(/assets/img/newsletter/)(.+) [NC]
# Is not a 2008-2011 newsletter
RewriteCond %{REQUEST_URI} !(.+)(11|10|09|08)_Newsletter.html$ [NC]
## -> RewriteRule to S3 Here <- ##

If I use this RewriteRule to point to the new subdirectory on S3 it will NOT redirect:

RewriteRule ^(/assets/img/newsletter/)(.+) https://s3.amazonaws.com/mybucket/newsletters/legacy/$2 [R=301,L]

However if I use a blanket expression to capture the entire file path it WILL redirect:

RewriteRule ^(.*)$ https://s3.amazonaws.com/mybucket/newsletters/legacy/$1 [R=301,L]

Why does it only work with a "match everything" expression but not a more specific expression?

kmgdev
  • 125
  • 1
  • 9
  • the `^(/assets/img/newsletter/)(.+)` regex does match the Request URI `/assets/img/newsletter/Jan12_Newsletter.html`. what does the rewrite log says? I usually put it on RewriteLogLevel 5. – Petter H Aug 18 '14 at 20:22
  • @PetterH It seems to match when I test it in [Regexr](http://regexr.com/39bdn) and the [.htaccess tester](http://htaccess.madewithlove.be/). – kmgdev Aug 18 '14 at 20:54
  • It is very strange since you rewritecond matces with that excact same regex so maybe there are some junk chars or something. It would be interresting to see the rewritelog... – Petter H Aug 18 '14 at 21:00

2 Answers2

1

The RewriteRule has some not needed stuff, which could cause this behavior.

Try this instead:

RewriteRule ^/assets/img/newsletter/(.+)$ https://s3.amazonaws.com/mybucket/newsletters/legacy/$1 [R=301,L]

Here I use the "one-or-more" quantifier to regex, so that $1 cannot be empty at any point.

Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
1

Since you capture the part of the URI you are interested in already in the first RewriteCond block, you don't have to capture it again to do the RewriteRule, and since both of your RewriteConds are met, there's no need to parse the URI a third time, so a simple caret would do it.

# Is it in the newsletters directory
RewriteCond %{REQUEST_URI} ^/assets/img/newsletter/(.+) [NC]
# Is not a 2008-2011 newsletter
RewriteCond %{REQUEST_URI} !(?:11|10|09|08)_Newsletter.html$ [NC]
RewriteRule ^ https://s3.amazonaws.com/mybucket/newsletters/legacy/%1 [R=301,L]

Therefore this should do the trick (matches from RewriteConds are prefixed with an % in stead of $).

It may not be explaining why your RewriteRule does not match because it looks OK to me, but using this method, it is unnceccesary.

Petter H
  • 3,443
  • 1
  • 16
  • 19