Creating subdomain to redirect any page or directory

October 28, 2014 7.8k views

Using Ubuntu 12.04 running wordpress.

I want to add subdomain to redirect any sub-directory or page.

For example:
My site:
Redirect: to

How can I do that?

3 Answers

simple way to do this is a 2-part solution:

in the .htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\
RewriteCond %{HTTP_HOST} ^(.+)
RewriteRule ^([^/]*)$ [P,L,QSA]

in the vhost config, add (below ServerName):

ServerAlias *

You will need to enable .htaccess by changing

AllowOverride None


AllowOverride All

This will change allow people to visit

and actually get
  • Why does it take so long? Do you really think this is the easiest way to do that?

  • Actually, no. That’s not the best way. It is the easiest, just not best.

    the best way is to have your code detect the sub-domain being called and serve out content for that page.


    $DOMAIN = str_replace("","",$URL);
    echo $DOMAIN
  • I don’t understand these PHP codes. What will the code do?

  • It’s example code. What it does is grabs the URL they requested (the domain name), strips off your top level domain (, then echos out what is left.

I found my best solution.

Added these lines to .htaccess file.

RewriteCond %{HTTP_HOST} ^sub\.mysite\.com$ [NC]
RewriteRule ^(.*)$1 [L,R]
Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!