Search code examples
regexapache.htaccessmod-rewriteurl-rewriting

RewriteCond file exists


Such a simple problem but htaccess and I have never got along.

  1. Serve the file if it exists.
  2. If the URI is just / and if index.html exists then serve index.html
  3. Otherwise serve app.php

Here is .htaccess:

# Disable the directory processing, Apache 2.4
DirectoryIndex disabled xxx
    
RewriteEngine On
    
# Serve existing files
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]
    
# For / serve index.html if it exists
RewriteCond %{REQUEST_URI} ^/$
RewriteCond    index.html -f
RewriteRule .? index.html [L]
    
# Otherwise use front controller
RewriteRule .? app.php [L]

It works if I comment out the RewriteCond index.html -f line as long as index.html does in fact exists. But I also want to check for index.php so I need the file exists check. And if nothing else I'd like to understand why the posted lines do not work.


Solution

  • This should work:

    # Disable the directory processing, Apache 2.4
    DirectoryIndex disabled xxx
        
    RewriteEngine On
        
    # Serve existing files
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]
        
    # For / serve index.html if it exists
    RewriteCond %{DOCUMENT_ROOT}/index.html -f [NC]
    RewriteRule ^/?$ index.html [L]
        
    # Otherwise use front controller
    RewriteRule ^ app.php [L]
    

    Remember that RewriteCond with -f or -d needs full path to the file or directory that's why you need to prefix the filename with %{DOCUMENT_ROOT}/. No need to escape dots here.