Search code examples
apache.htaccessmod-rewrite

htaccess - how deny access to all resource expect for that resource called from hostname and gived file


i have this .htaccess:

# Rewrite URL
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteBase /

  RewriteCond "%{HTTP_HOST}" "!^www.mydomain.com" [NC]
  RewriteCond "%{REQUEST_URI}" "!^/myfile.html" [NC]
  RewriteRule \.*$ - [F,NC]

</IfModule>

I want DENY access to ALL resources, EXCEPT for:

  1. all resource from HTTP_HOST (es. www.mydomain.com);
  2. specific gived file (es. myfile.html).

The code above not work. As i can solve it? Thanks

PS: In other words, i want to do something like:

<?php

    if ( 
        $_SERVER["REMOTE_ADDR"] !== "www.mydomain.com" ||
        $_SERVER["REQUEST_URI"] !== "/myfile.html"
    ) {
        // redirect 403
    } 
} 

?>

Solution

  • Based on your comments I believe you need to check for referrer. You may try this rule:

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
    RewriteCond %{REQUEST_URI} !/myfile\.html$ [NC]
    RewriteRule \. - [F]
    

    Just keep in mind that HTTP_REFERER based blocking is not very strong protection as clients can spoof this header.

    Testing curl commands:

    curl --referer 'http://example.com/' -IL 'http://yourdomain.com/'
    
    HTTP/1.1 403 Forbidden
    Date: Thu, 08 Apr 2021 09:28:17 GMT
    Server: Apache/2.4.46 (Unix) OpenSSL/1.1.1j PHP/8.0.3
    Strict-Transport-Security: max-age=31536000
    Content-Type: text/html; charset=iso-8859-1
    
    curl --referer 'http://yourdomain.com/' -IL 'http://yourdomain.com/'
    
    HTTP/1.1 200 OK
    Date: Thu, 08 Apr 2021 09:27:47 GMT
    Server: Apache/2.4.46 (Unix) OpenSSL/1.1.1j PHP/8.0.3
    Strict-Transport-Security: max-age=31536000
    X-Powered-By: PHP/8.0.3
    Content-Type: text/html; charset=UTF-8
    

    References: