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.

  • how failed? It just doesn't redirect? Did you check error logs? – Aerik Nov 10 '11 at 20:23
  • sorry. The webbrowser is redirected to the url recherche?search_query=${REQUEST_URI} , ${REQUEST_URI} is not replaced, it is as you can read it here. – 7seb Nov 10 '11 at 21:57

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.

  • I don't understand, if your requested file is not a file neither a directory, what could it be ? – vdegenne Nov 14 '11 at 11:21
  • @Oddant Have a look at URL of this question -- do you think that there is real file with such path? That's just a "nice" URL. That's why this rule is placed at the end of other rules. Now .. if requested resource is not a real file or folder .. and it was not already processed (converted/rewritten from nice URL to a real file/folder), then it is a request to non-existing resource (as this is the last rule, which works like 404 handler, just in "manual" mode). – LazyOne Nov 14 '11 at 17:09
  • @LazyOne thanks for the explanation, it's pretty clear now. – vdegenne Nov 14 '11 at 17:25
  • Will doing this make your site quality in Google lowered? – leeand00 Jun 28 '12 at 18:29
  • In the last RewriteRule, adding R=404 takes me to a 404 page instead of the search page. Also it tacks on a nasty / at the beginning. – leeand00 Jun 28 '12 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.