2

I want to know how to prevent hotlinking to resources on my site without hard coding the domain name.

I need this since the software will be used for multiple domains, and may be used as an installation. It would not be feasible to instruct every user to make changes in the htaccess file to enter their current domain.

I have come across a lot of code similar to this. but here as you can see you have to enter the domain name.

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !www.example.com [NC]
RewriteRule \.(gif|jpg|png)$ - [F,NC]

I have also come across the below snippet from this apache page, which seems to solve the problem. But for some reason cant get it to work.

RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
RewriteRule ^/images - [F]

Note: i have set up a local domain name to perform the tests. so i access my site as mysite.local instead of localhost/mysite

Is there a way i can prevent hotlinking without hard-coding the domain name in the htaccess ?

TheWebGuy
  • 31
  • 3
  • Just realized that the code given above from the apache page is for apache version 2.4. while i have version 2.2 on my local machine. – TheWebGuy Mar 25 '12 at 06:38
  • Quick clarification regarding your first parameter: Are you saying that the images will need to be available to some domains but not all (with your server acting as the image server for those whitelisted domains) or that the whole site will be portable, images and all, and you want to avoid hotlinking regardless of where the site gets "installed"? – Anthony Mar 25 '12 at 06:40
  • Well consider the site as an installation. which will be used by different clients for different purposes. apart from a few social sites like facebook, google, and ofcourse the domain that it is installed on, the images and other resources will need to be protected from hotlinking. for any other sites. – TheWebGuy Mar 25 '12 at 10:52

1 Answers1

0

Looking at the 2.2 documentation, I think it's actually a lot more simple back then than in 2.4. But test to be sure:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !%{HTTP_HOST} [NC]
RewriteRule ^/images - [F]
Anthony
  • 36,459
  • 25
  • 97
  • 163
  • Sorry, had a copy and paste error there. Still checking around to confirm need for the front and back slashes. – Anthony Mar 25 '12 at 07:05
  • I don't see why the above shouldn't work, since `%{HTTP_HOST}` should resolve to `www.example.com` (in their example). – Anthony Mar 25 '12 at 07:08
  • as I know, you can not use server variables in both arguments of `rewritecond`. – undone Mar 25 '12 at 08:34
  • I had tried this technique, but it didn't work. Also what happens when the url is entered as http://www.site.com and http://site.com how to tackle that ?. Note i have also added a rewrite rule to perform a 301 redirect to remove the www from the domain. – TheWebGuy Mar 25 '12 at 11:00