: .htaccess rule to redirect from 404 to search results When a user (or a bot) request on non existing page, I want to redirect him to the search results. I prefere to do it with the .htaccess
When a user (or a bot) request on non existing page, I want to redirect him to the search results. I prefere to do it with the .htaccess file using something like:
ErrorDocument 404 /recherche?search_query=${REQUEST_URI}
However, it fails; the web browser is redirected to the URL recherche?search_query=${REQUEST_URI} , ${REQUEST_URI} and is not replaced, it is as you can read it here.
More posts by @Tiffany637
1 Comments
Sorted by latest first Latest Oldest Best
The variable replacement will not work in ErrorDocument directive -- it will pass URL as is with no changes (maybe there are some special module that will perform such replacement -- I do not know).
If you want to use ErrorDocument directive, then you will have to grab the originally requested URL in the script itself (e.g. $_SERVER['REQUEST_URI'] in PHP). You can pass some special parameter to tell your 404 handler to execute such look up, e.g. ErrorDocument 404 /recherche?special-search=yes.
Another approach would be to use mod_rewrite, where such replacement is possible. For example:
Options +FollowSymLinks
RewriteEngine On
# redirect all requests to non-existing resources to special handler
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /recherche?search_query=%{REQUEST_URI} [L,R=404]
If you are using mod_rewrite already .. then such rule should be placed somewhere at the end of your rules list so it does not conflict with other rules.
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2025 All Rights reserved.