Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

In evaluating a rewrite rule that redirects to a specific URL and say the rewrite condition is met, would it be possible to use HTTP_HOST as part of the URL to be redirected to?

Example in question:

RewriteRule .*\.(jpg|jpe?g|gif|png|bmp)$ http://%{HTTP_HOST}/no-leech.jpg [R,NC]

The motive behind this question is a desire to create a single htaccess file that would match against an addon domain (on a shared hosting account) and an infinite amount of subdomains below it to prevent hotlinking of images.

share|improve this question

1 Answer 1

You can use %1 (and %2, etc) to access matches in preceding RewriteCond statements:

RewriteEngine On
# don't redirect no-leech.jpg or we'll end up in a loop
RewriteCond %{REQUEST_URI} !^/no-leech.jpg$
# match Host header and store
RewriteCond %{HTTP_HOST} (.*)
RewriteRule \.(jpg|jpe?g|gif|png|bmp)$ http://%1/no-leech.jpg [R,NC,L]

Test:

# GET -Sd http://localhost/foo.jpg
GET http://localhost/foo.jpg --> 302 Found
GET http://localhost/no-leech.jpg --> 200 OK

And with a different Host header:

# GET -SedH 'Host: foo.bar.com' http://localhost/foo.jpg
GET http://localhost/foo.jpg --> 302 Found
GET http://foo.bar.com/no-leech.jpg --> 200 OK
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.