Been surfing around for a solution for a couple days now.
How do I enable Apache hotlink protection without hardcoding my domain in the config file so I can port the code to my other domains without having to update the config file every time?
This is what I have so far:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.(com|net|org) [NC]
RewriteRule \.(gif|ico|jpe|jpeg|jpg|png)$ - [NC,F,L]
... And this is what Apache suggests:
SetEnvIf Referer example\.com localreferer
<FilesMatch \.(jpg|png|gif)$>
Order deny,allow
Deny from all
Allow from env=localreferer
</FilesMatch>
... both of which hardcode the domain in their rules.
The closest I came to finding any info that covers this is right here on ServerFault, but the conclusion was that it cannot be done. Based on my research, that appears to be true, but I didn't find any questions or commentary dedicated soley to this question.
If anyone's curious, here is the link to the Apache 2 docs that cover this topic.
Note that Apache environment variables (e.g. %{HTTP_REFERER}
) cannot be used in the RewriteCond
's CondPattern argument.
What about checking to see if Host matches the Referrer? E.g.Edit
This won't work, as stated by the OP. For Apache 2.4 you can use:
For 2.2, you could write a small handler in mod_perl or mod_python that could perform the compare and issue the 403 error.
To achieve this with mod_python:
Create a file in your docroot (in my case /var/www/) called
hotlink.py
In you Apache config:
Now all requests for .jpg and .gif will be first checked by hotlink.py. With mod_python you can also check against the
req.server.server_hostname
attribute to check againstServerName
instead of the incoming Host header.