Wanted to redirect our old standby, pastebin.zentrack.net to the new location, dev.zentrack.net/pastebin. Took a bit of mojo to find the answer to that problem. I decided on using apache and bypass virtualmin’s admin tools.
The “Rewrite” Approach
Here is an approach using a rewrite rule, that preserves files and query parms from the original entry. This takes widgets.mysite.com/files/?id=20 and redirects it to www.mysite.com/widgets/files/?id=20:
RewriteCond %{HTTP_HOST} ^(www\.)?subdomain\.mainsite\.com
RewriteRule (.*) http://www.mainsite.com/subdirectory$1 [L,R=permanent] |
%{HTTP_HOST} is an apache variable that refers to the current domain entered in browser.
(www\.) makes it possible to redirect widgets.mysite.com or www.widgets.mysite.com.
/subdirectory is where you specify which directory the redirect drops them in.
(/.+)? bit is what adds on any details after the url.
[L, R=permanent] is based on Apache’s RewriteCond options, and tells apache we actually want to change the url in the browser, instead of just showing the correct page at this url.
The “Redirect” Approach
A simpler approach is to create a hard redirect like the following. This takes widgets.mysite.com/files/?id=20 and redirects it to www.mysite.com/widgets/:
ServerAlias subdomain.mainsite.com RewriteEngine on RewriteCond %{HTTP_HOST} ^subdomain.mainsite.com$ [OR] RewriteCond %{HTTP_HOST} ^www.subdomain.mainsite.com$ RewriteRule ^(.*)$ http://www.mainsite.com/subdirectory [R=301,L] |
This goes into the apache config, inside mainsite.com’s VirtualHost directive.
ServerAlias directive allows the main site to also accept queries for the subdomain.
You may also need to add a DNS entry, depending on your setup.
RewriteCond with www.subdomain.mainsite.com is optional and recommended–if you remove it, also remove the [OR].