Knowledgebase

How to redirect requests for content only if it does not exist

You can use mod_rewrite to check whether a requested file exists in the requested location, and if it doesn't you can redirect the request to another path or URL address.

For example, let's say that requests for files within yourdomain.com/images should be redirected to yourdomain2.com/images only if the requested file does not exist in yourdomain.com/images. In this case you can put a few directives in the .htaccess file that's in the public_html directory of the hosting account for yourdomain.com:

#Redirect files from yourdomain.com/images to yourdomain2.com/images only
#if the file doesn't exist in yourdomain.com/images

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/(.*) http://yourdomain2.com/images/$1 [R]

So with this example if somebody requests yourdomain.com/images/image1.jpg and the file image1.jpg exists in that location it will be displayed; if it doesn't exist there, the request will be redirected to yourdomain2.com/images/image1.jpg.

Here is a brief explanation of how this works. The RewriteCond directive has two arguments: the variable REQUEST_FILENAME and !-f. The variable is the path to the requested file; the -f argument tells the engine to check whether the filename exists and the exclamation mark before it makes this a negative condition, meaning that the condition will be fulfilled and consequently the rewrite rule applied only if the filename does not exist. The part (.*) in the RewriteRule directive will actually match any requested filename which is in the images directory of yourdomain.com. The second argument of the RewriteRule directive is the URL to which the request will be redirected; the $1 will be replaced with the filename of the requested file (whatever is matched by the part in the brackets of the first argument of the RewriteRule).

For general information on the mod_rewrite directives and their syntax read the tutorial on mod_rewrite directives.

In case you want to redirect all Not found errors to a particular page you can easily do that with the ErrorDocument directive. For more information check out the article on redirecting errors and changing the error messages.

Was this answer helpful?

 Print this Article

Also Read