Reputation: 34673
I have a sub domain that I intend to use for CDN at some point: images.example.com
. The requests on that subdomain should look like http://images.example.com/path/to/some/image.jpg
. But currently everything is still hosted on the same server, and the server is configured to have images.example.com
as alias for example.com
.
This way both requests will work:
http://images.example.com/path/to/some/image.jpg
http://example.com/path/to/some/image.jpg
But also other valid request will resolve on both subdomain and tld:
http://example.com/blog/post/Some-Interesting-Non-Image-Content
http://images.example.com/blog/post/Some-Interesting-Non-Image-Content
Let's assume that if an image is streamed, the URL will have image extension. I want to write a rewrite Cond/Rule for .htaccess
that will redirect all requests on images.example.com
, that do not end in image extension (\.gif|\.png|\.jpeg|\.jpg)
to example.com
. Also I'd like to have the opposite rule. If a request with (\.gif|\.png|\.jpeg|\.jpg)
comes to example.com
- redirect it to images.example.com
.
I tried several things, they seem to fail (I have trouble working out .htaccess regular expressions):
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]
Upvotes: 2
Views: 270
Reputation: 143856
The %{HTTP_HOST}
variable contains only the hostname, as it is transmitted in the HTTP "Host" request header. Therefore, you can't attempt to match things like the request URI in it. You can do that in either the regex pattern in the RewriteRule
or against the %{REQUEST_URI}
variable. Try:
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]
The NC
flag is to indicate the match to be case insensitive.
Upvotes: 1