How to prevent access to multiple file types in htaccess

367 Views Asked by At

I'm trying to protect a few sitemap files from public access. The only ones that are allowed to have access are IP ranges from our lovely Google crawlers.

For example - the Apache module mod_authz_host.c did the job well. Until now....

<FilesMatch "(sitemap\.xml|sitemap_index\.xml|page-sitemap\.xml)$">
    Require ip 1.2.3.4
    Require ip 1.2.3.0/16
</FilesMatch>

It hasn't worked so far.

Where has the error crept in here?

1

There are 1 best solutions below

4
On

Updating my answer (thanks for the constructive comments from @MrWhite and @Boppy - I really appreciate it):

Using Apache 2.2 and Apache 2.4 auth directives on the same server can cause problems and/or errors. Only use the code that applies to the version of Apache to avoid conflicts

  • Apache 2.2 uses the authz_host_module to control access with directives like Deny, Allow, and Order.
  • Apache 2.4 also uses the authz_host_module for access control, but also uses the authz_core_module that provides the new/+10 years old require directive.

For example, if I want to deny all access:

Apache version 2.2

Order deny,allow
Deny from all

Apache version 2.4:

Require all denied

About the usage of <IfModule>

If I don't know the version of Apache I'm using, I can use code with conditional statements that will detect the correct version of the web server and apply the correct rule accordingly.

# Apache 2.2

<IfModule !authz_core_module>
<FilesMatch "\.(md|exe|sh|bak|inc|log|sql)$">
    Order Deny,Allow
    Deny from all
</FilesMatch>
<IfModule>

<IfModule !authz_core_module>
<FilesMatch "(sitemap\.xml|sitemap_index\.xml|page-sitemap\.xml)$">
    Order Deny,Allow
    Deny from all
    Allow from 1.2.3.4
    Allow from 1.2.3.0/16
</FilesMatch>
<IfModule>


# Apache 2.4

<IfModule authz_core_module>
<FilesMatch "\.(md|exe|sh|bak|inc|log|sql)$">
    Require all denied
</FilesMatch>
<IfModule>

<IfModule authz_core_module>
<FilesMatch "(sitemap\.xml|sitemap_index\.xml|page-sitemap\.xml)$">
    <RequireAll>
            Require ip 1.2.3.4
            Require ip 1.2.3.0/16
    </RequireAll>
</FilesMatch>
</IfModule>