I used this code in my .htaccess
file and it is working great to prevent hotlinking:
RewriteEngine On
RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/.*
RewriteRule \.(gif|jpg|jpeg|png|tif|pdf|wav|wmv|wma|avi|mov|mp4|m4v|mp3|zip?)$ - [F]
Now I want to allow one of my subdomains (cdn.example.com
) to access my files using a GET request.
It is not possible to add http_reffer to my GET request! I should only handle it with .htaccess
.
How should I add my subdomain as an exception in this code?
CodePudding user response:
RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/.*
Use the following condition instead to allow for an optional cdn
subdomain:
RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://(cdn\.)?\1/
(The trailing .*
is not required.)
UPDATE#1:
It is not possible to add http_reffer to my GET request!
Not sure exactly what you mean by this, but if the Referer
header is not being sent with these requests for some reason (perhaps you have a restrictive Referrer-Policy?) then you will likely need to allow an empty referer.
To allow an empty Referer
, add the following as the first condition:
RewriteCond %{HTTP_REFERER} !^$
:
However, this will also allow direct requests. But due to the unreliable nature of the Referer
header you really need to allow an empty Referer
header anyway since some legitimate users might be suppressing it.
Aside: These directives to prevent hotlinking also block search engines - if that is a concern?
UPDATE#2:
i have another server for cdn.mydomain.com . and on that server i have a php script that will convert images to specific format . i should allow this script to read images from main domain
:
i can't edit that php script to change request method
Ideally, the script would be sending a custom HTTP request header indicating that the request is coming from your "CDN". You could then check for this in the above directive to allow the request.
If all these requests are coming directly from this other server then you can perhaps allow all requests from this server - identified by the server's IP address.
For example, if 203.0.113.111
is your server's IP address, then:
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !=203.0.113.111
RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/
RewriteRule \.(gif|jpg|jpeg|png|tif|pdf|wav|wmv|wma|avi|mov|mp4|m4v|mp3|zip?)$ - [F]