DEV Community 👩‍💻👨‍💻

Cover image for Apache - Rewrite all URIs to a single file
Lyubomir Angelov
Lyubomir Angelov

Posted on • Originally published at lyubomir-angelov.com

Apache - Rewrite all URIs to a single file

This week I had to help a friend with his new small ReacJS website running on Apache.

His problem was that URIs which does not exist the Apache was returning as 404 pages, he needed a common rule used by a lot of PHP frameworks, Rewrite all URIs which are not Files or Directories to /index.html

Example URL www.example.com/myprofile to actually load www.example.com/index.html and let the ReactJS route do his work and show what it needs.

In that case, you might write something like this:


    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.html [L]

What is this doing, it will check the URI either exists as a file or is a directory if it is NOT, it will call index.html. The [L] means that this will be the LAST match and will stop there, will not continue if we have other rules below that.

This is code is ok, not so simple and you can mess up the conditions, for example, I have seen a lot of [OR] next to RewriteCond %{REQUEST_FILENAME} !-f [OR] which will not work in our case above.

If you need this simple Rewrite rule, you might use Apache command available after 2.2.16 version


    FallbackResource /index.html

This will do the same as the above 4 lines if the URI is not found on the server, ie. not a File or a Dir, it will load to /index.html

This command is not part of mod_rewrite, but of mod_dir, if you don't have it enabled, run sudo a2enmod dir and restart the Apache.

Top comments (0)

Create an Account!

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.