I rebuilt my old site. There was a subdomain to that old site: forum.example.com
. Now, it does not exist anymore. A person who accesses my site using forum.example.com
should be redirected to example.com
.
My .htaccess
file:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
If the host is not example.com
, redirect to example.com
. Shouldn't forum.example.com
fit in the condition?
Now for the optional part of the question, if someone could explain to me the rule above, it would be great.
Here's what I understand in the above rule:
If the host is NOT example.com
(!^example.com$
)
redirect to http://example.com
.
What I don't understand is the first part of the rule regex: ^(.*)$
, and then the reference to it ($1
). How come matching everything can be put as the requested file path? Wouldn't it do something like this?
http://example.com/http://www.example.com/[requested file]
Best Answer
The above code looks at the HTTP host of the connecting browser. Note that .htaccess can only work on a request that can reach the webserver. This will work for
forum.example.com
, but only ifforum.example.com
actually loads the content in the directory that the .htaccess file resides in. If you do not have the DNS records set up (for example, a*
A record or aforum
A record) then it will not even go to the site at all, because the DNS is invalid. Also, Apache must be set up to load the site for that VirtualHost. So it must be listed in the Apache configuration as well before .htaccess can forward the URL as specified.For your second question, in the
RewriteRule
part^(.*)$
, this only matches the file that is accessed off the server. TheRewriteCond
part only applies the rule on certain hostnames, then^(.*)$
specifies that any request follow the rewrite rules.So the above .htaccess code will apply for all requests after the
/
if the host does not equalexample.com
.Let me know if you need any further explanation.