Knowledgebase

How to redirect content to another site with mod_rewrite

You can use mod_rewrite to redirect content from your hosting account to another website. To do this you need to put at least a couple of directives in an .htaccess file on your account. The .htaccess file can be in the public_html directory on your account (the root web-accessible directory), or in case the content is in a subfolder you can also use an .htaccess file that's in the particular subfolder.

You have to use at least the RewriteEngine and RewriteRule directives in order to redirect content. For example, let's say that you want to redirect the files from yourdomain.com/images to yourdomain2.com/images. You can do that by putting the following rules in the .htaccess file that's in the public_html directory:

#Redirect the content from yourdomain.com/images to yourdomain2.com/images
RewriteEngine On
RewriteRule ^images/(.*) http://yourdomain2.com/images/$1 [R]

This is done in almost the same way as redirecting content from one location on your hosting account to another location within the same account. The difference is that the destination address (the Substitution argument) in the RewriteRule directive is a full URL address. You can also check out the article on redirecting content within the same account with mod_rewrite.

The R flag at the end of the RewriteRule stands for an external redirect. By default, the HTTP status of the redirected content is 302 (temporary). If you want to, you can change the status with the help of the R flag. In case you want to know more about it, check out the article on changing the HTTP redirect status.

The above example redirect can also be achieved with the Redirect or the RedirectMatch directive. For more information read the article on redirecting with the Redirect directive and the article on redirecting with RedirectMatch.

However, if you want to include some conditions that have to be met for the redirect to be performed, then you should use mod_rewrite. Conditions can be set with the RewriteCond directive. For more information on its syntax and how to use it, as well as for basic information about the other mod_rewrite directives, check out the tutorial on mod_rewrite.

Was this answer helpful?

 Print this Article

Also Read