Search code examples
apache.htaccesswhitelist

Can .htaccess be used to filter a white list?


Is there a way of generating a white list of acceptable files or types? I have seen recipes for rejecting file requests — is it possible to reject all but those from a list?

The sort of white list I had in mind would be something like:

*.html;*.jpg;*.css;*.php

… etc

I would assume that other file requests could result in a 404 File Not Found

Thanks


Solution

  • You can create a whitelist like this in your root .htaccess:

    # deny everything first
    Order Deny,Allow
    Deny from  all
    
    # then allow selected whitelisted extensions
    <FilesMatch '\.(php|html|jpe?g|css|js)$'>
      Allow from all
    </FilesMatch>
    

    EDIT: To return 404 for non-whitelisted files use this rule:

    RewriteEngine On
    
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule !\.(php|html|jpe?g|css|js)$ - [L,NC,R=404]
    
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.+)$ /index.php?page=$1 [QSA,L]