Search code examples
apache.htaccessmod-rewritecase-insensitive

Case-insensitive file check for RewriteCond


I have a .htaccess file which tests for a specific file and runs a PHP script if it's present, and redirects to another web if it's not.

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/directory/$1 -f
RewriteRule ^(.+\.png)$ process.php?file=$1 [QSA]

RewriteRule ^(.+\.png)$ http://other.website.com/$1

I could run the PHP script directly and do the redirect, but it's faster this way. However, I need to make the RewriteCond check case-insensitive. I have tried setting all flags and enabling spelling check, but to no avail.

RewriteEngine on
CheckSpelling on
RewriteCond %{DOCUMENT_ROOT}/directory/$1 -f [NC]
RewriteRule ^(.+\.png)$ process.php?file=$1 [QSA,NC]

RewriteRule ^(.+\.png)$ http://other.website.com/$1

The spelling module is enabled in httpd.conf, and .htaccess files can modify all possible settings, but it still works the same as before, not redirecting if a file with different cased filename is entered.


Solution

  • Try using the tolower mapping in your Apache config. First, create a map for the tolower call in your httpd.conf (or apache2.conf or VHost config):

    RewriteMap lc int:tolower
    

    Next, in your condition check, convert the $1 to lowercase:

    RewriteEngine on
    RewriteCond %{DOCUMENT_ROOT}/directory/${lc:$1} -f [NC]
    RewriteRule ^(.+\.png)$ process.php?file=$1 [QSA,NC]
    
    RewriteRule ^(.+\.png)$ http://other.website.com/$1
    

    Please note that, for the above to work, your files should always be in lower alphabets.