Search code examples
html.htaccessmod-rewritehttp-refererhotlinking

.htaccess - hotlink prevention not working for other hosted domains


This is probably a simple solution, but I have a hosting account and a primary domain associated with it. I also have other domains 'sub-hosted' on the same account. I setup hotlink prevention at the document root. However, it only works for the primary domain. The sub-hosted domains continue to allow hotlinking.

Here is the code I'm using. What modifications might be necessary to prevent hotlinking for the other domains on the same host? Thanks

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?PRIMARY-DOMAIN.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?SUB-HOST1.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?SUB-HOST2.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?SUB-HOST3.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://www.PRIMARY-DOMAIN.com/Images/Hotlink/hotlink.gif [NC,R,L]
RewriteCond %{REQUEST_URI} !^/Images/Hotlink/

Solution

  • In the document root, the subdomains point to folders with the same name.

    If these subdirectories also have their own .htaccess files that contain mod_rewrite directives then (by default) these directives will completely override the mod_rewrite directives in the parent .htaccess file (in the main domain). So, your "hotlinking" directives will never get processed.

    You either need to enable mod_rewrite inheritance. However, this can come with caveats if you have other directives in the parent .htaccess file. And depends on whether you have Apache 2.2 or 2.4+

    For example, on Apache 2.4, you can include the following directive in the parent .htaccess file to process the "hotlinking" directives before the directives in the subdomain's .htaccess file:

    RewriteOptions InheritDownBefore
    

    But note that this could break your site, depending on what other directives you have in the .htaccess file. mod_rewrite inheritance works by literally copying the directives in-place - this can be a problem if you are relying on the directory-prefix.

    Or, you reproduce these hotlinking directives in the .htaccess files of each subdirectory/subdomain.

    RewriteRule \.(jpg|jpeg|png|gif)$ http://www.PRIMARY-DOMAIN.com/Images/Hotlink/hotlink.gif [NC,R,L]
    RewriteCond %{REQUEST_URI} !^/Images/Hotlink/
    

    These directives are the wrong way round. The RewriteRule should be last.