2

我有一个打算在某个时候用于 CDN 的子域:images.example.com. 该子域上的请求应如下所示http://images.example.com/path/to/some/image.jpg。但目前所有内容仍托管在同一台服务器上,并且服务器配置为images.example.com具有example.com.

这样两个请求都可以工作: http://images.example.com/path/to/some/image.jpg http://example.com/path/to/some/image.jpg

但其他有效请求也将在子域和 tld 上解析: http://example.com/blog/post/Some-Interesting-Non-Image-Content http://images.example.com/blog/post/Some-Interesting-Non-Image-Content

假设如果图像被流式传输,则 URL 将具有图像扩展名。我想写一个重写条件/规则.htaccess,它将重定向所有请求images.example.com,而不是以图像扩展名结尾(\.gif|\.png|\.jpeg|\.jpg)example.com。我也想有相反的规则。如果一个请求(\.gif|\.png|\.jpeg|\.jpg)来了example.com- 将它重定向到images.example.com.

我尝试了几件事,它们似乎都失败了(我无法解决 .htaccess 正则表达式):

RewriteCond %{HTTP_HOST} ^images\.example\.com (.*) (?!\.jpg|\.gif|\.jpg|\.jpeg)$
RewriteRule ^(.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^example\.com (.*) (\.jpg|\.gif|\.jpg|\.jpeg)$
RewriteRule ^(.*) http://images.example.com/$1 [R=301,L]
4

1 回答 1

1

%{HTTP_HOST}变量包含主机名,因为它在 HTTP“主机”请求标头中传输。因此,您不能尝试匹配其中的请求 URI 之类的内容。您可以在变量中RewriteRule或针对%{REQUEST_URI}变量的正则表达式模式中执行此操作。尝试:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^images\.example\.com$ [NC]
RewriteRule !\.(jpe?g|gif|ico|png)$ http://www.example.com%{REQUEST_URI} [R=301,L,NC]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule \.(jpe?g|gif|ico|png)$ http://images.example.com%{REQUEST_URI} [R=301,L,NC]

NC标志用于指示匹配不区分大小写。

于 2012-12-27T03:22:25.050 回答