As promised in our previous two articles (Perform Internal Redirection with mod_rewrite and Show Custom Content Based on Browser), in this post we will explain how to perform a redirection to a resource that has been moved from one server to a different server in Apache using mod_rewrite module.
However, you want this change to be transparent to your users so that they are still able to access the docs at the usual URL.
In the following example, a file named
assets.pdf has been moved from /var/www/html in 192.168.0.100 (hostname: web) to the same location in 192.168.0.101 (hostname: web2).
In order for users to access this file when they browse to
192.168.0.100/assets.pdf, open Apache’s configuration file on 192.168.0.100 and add the following rewrite rule (or you can also add the following rule to your .htaccess file):
RewriteRule "^(/assets\.pdf$)" "http://192.168.0.101$1" [R,L]
$1 is a placeholder for anything that matches the regular expression inside parentheses.
Now save changes, don’t forget to restart Apache, and let’s see what happens when we attempt to access assets.pdf by browsing to 192.168.0.100/assets.pdf:
In the above below we can see that the request that was made for assets.pdf on 192.168.0.100 was actually handled by 192.168.0.101.
# tail -n 1 /var/log/apache2/access.log
In this article we have discussed how to perform a redirection to a resource that has been moved to a different server. To wrap up, I’d strongly suggest you take a look at the mod_rewrite guide and Apache redirect guide for future reference.
As always, feel free to use the comment form below if you have any concerns about this article. We look forward to hearing from you!