How can I write a RewriteRule
that first checks if the requested file exists, and if not, redirects to the root page:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule "^/(.*)" "/" [L]
For example
http://example.com/not_existing_file
should redirect to http://example.com
.
This doesn't work however. What's wrong here?
Your condition, checking that the request does not map to an existing file, would seem to be correct. However, your
RewriteRule
does not redirect, it internally rewrites the request instead. It would also seem to trigger a rewrite loop (500 error)?Try the following instead:
The
R
flag is required here in order to trigger an external redirect. This would only redirect/<something>
, rather than/<anything>
, as in your original code.Change the
302
(temporary) redirect to301
(permanent) once you are sure this is working OK - if that is what's required. Makes for easier testing, since 301s are otherwise cached hard by the browser.This also assumes this is in the main server config, not
.htaccess
or<Directory>
section.