Search code examples
apache.htaccessurl-rewriting

How to use .htaccess to serve html file without extension if exists or fallback to index.php


Using apache .htaccess is it possible to achieve the following:

  • A url without extension is called e.g. /, /terms, /products/one.
  • If the relevant html file exists (index.html, terms.html, products/one.html) then it is served.
  • If it does not exist, then index.php is called with a query string variable for e.g. index.php?path=terms.

How can we do that?


Solution

  • Ended up creating the below .htaccess code, see the comments for description:

    RewriteEngine On
    RewriteBase /
    
    # if any html exists based on current path then serve it
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.*)$ $1.html [L]
    
    # if index.html exists then serve it if filepath is empty (checked by RewriteRule ^$)
    RewriteCond %{DOCUMENT_ROOT}/index.html -f
    RewriteRule ^$ /index.html [L]
    
    # any thing left should go to index.php as path
    # the RewriteCond !-f is used to avoid index.php loopback
    # the RewriteCond !-d is NOT used so that if folder exists then it does not show directory listing
    # may want to use some condition to show index.html in that folder if exists
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?path=$1 [L]
    

    Checked all scenarios and seem to work!

    For e.g.

    • if / is called then it loads index.html if it exists, else it loads index.php
    • if any path is called and its relevant html exists then it loads else index.php is called with that path
    • made sure that static files like javascript and images etc also work
    • made sure php files also work if they exist