.htaccess rule to redirect from 404 to search results
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.
Related videos on Youtube
Comments
-
7seb almost 2 years
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. -
vdegenne over 12 yearsI don't understand, if your requested file is not a file neither a directory, what could it be ?
-
LazyOne over 12 years@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).
-
leeand00 about 12 yearsWill doing this make your site quality in Google lowered?
-
leeand00 about 12 yearsIn 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.
-
Admin over 11 yearsI tested your solution but it not effect with my site. Can give me more solution?