问题描述:

Something is wrong with the following rewrite rule. I thought I was doing it the right way since i copied from a book other than it's supposed to redirect to another domain.

I got the following url:

http://www.domaina.com/some-Text-is-here-B40178.jpg

the image is located at the url:

http://www.domainb.com/imgs/B40178.jpg

How should the underneath rewrite rule be written in order to make this work?

RewriteRule ^.*-B([0-9]+)\../$ http://www.domainb.com/imgs/B$1 [L]

网友答案:

Your rule is missing the extension so it's not matching. Also it looks like you have an extra / on the end. If it's always jpg you could add that. Or just match anything at the end.

Also you need to capture that extension as well.

Matches "jpg"

RewriteRule ^.*-B([0-9]+\.jpg)$ http://www.domainb.com/imgs/B$1 [R,L]

Matches anything

RewriteRule ^.*-B([0-9]+\..+)$ http://www.domainb.com/imgs/B$1 [R,L]

My preferred method, match certain image types:

RewriteRule ^.*-B([0-9]+)\.(jpg|gif|png)$ http://www.domainb.com/imgs/B$1.$2 [R,L]

EDIT Missed that you were redirecting to another domain. You need the R flag as well. I've added it.

网友答案:

You need to mark the rule as a Redirect, like this:

RewriteRule ^.*-B([0-9]+)\../$ http://www.domainb.com/imgs/B$1 [R,L]

EDIT: you also need to tack on the file extension. I'm going to be lazy and assume they're all JPGs:

RewriteRule ^.*-B([0-9]+).jpg$ http://www.domainb.com/imgs/B$1.jpg [R,L]
网友答案:

In the end I found a better solution that doesn't use a redirect:

 RewriteCond  %{REQUEST_URI}  !^$
 RewriteCond  %{REQUEST_URI}  !^/
 RewriteRule  .*              -    [R=400,L]
 RewriteRule ^.*-B([0-9]+)\.(jpg|jpeg|png|gif|JPG|GIF|PNG|JPEG)$ http://www.domain.com/imgs/B$1.$2 [P,L]`

So in the URL it won't look like the image doesn't come from another domain. P stands for Proxy (http://httpd.apache.org/docs/2.4/rewrite/proxy.html)

相关阅读:
Top