Timo002 Timo002 - 4 months ago 42
Apache Configuration Question

mod_rewrite rule to check if file exists on server

I need a mod_rewrite rule and I can't figure it out myself.

The request URL can be:


I want to check if the following file exists:


If this file exists, than it should serve the file. If not exist, then continue to the next mod_rewrite rule.

Is this possible with mod_rewrite? If yes, how?


Create a sub.domain.com/.htaccess if it doesn't exist with this code:

RewriteEngine On

# ignore files and directories from all rewrite rules    
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule (^|/)index\.php$ - [L,NC]

RewriteCond %{DOCUMENT_ROOT}/sub.domain.com/cache/$1 -f
RewriteRule ^(?!cache/)(.+\.\w+)$ cache/$1 [L,NC]

#Else go to controller
RewriteRule ^(|(.*)/)([0-9]+x[0-9]+|[a-z]+[0-9]+|original)/(.*)$ ../index.php?path=$4&format=$3&folder=sub.domain.com [L,QSA]


  • (?!cache/) - negative lookahead to ignore requests that already have cache/
  • (.+\.\w+) - Match any request with at least an extension and captures it in $1
  • 1st rule has 2 RewriteCond that checks if request is NOT for an existing file or directory
  • 2nd RewriteCond checks presence of $1 file using full path in cache/ directory
  • If condition succeeds then in the target we just prefix the relative file path with cache/