Redirect Wildcard Subdomains to Primary Domain on Media Temple’s (dv) Hosting

Redirect Wildcard Subdomains to Primary Domain on Media Temple's (dv) HostingIn a recent post wherein I questioned the legitimacy of W3schools’ subdomains, someone pointed out that my own site was suffering from a somewhat related problem.

Basically, if anyone typed a random subdomain in place of the “www”, the subdomain would remain in place in the address bar without any redirection occurring. So for example, if you visited peanutbuttersandwich.impressivewebs.com, the site would display as normal, except with the “peanutbuttersandwich” part still intact.

What’s worse is that I have other domains on my current hosting plan, and impressivewebs.com is the primary domain. So if someone typed in a subdomain for one of the other domains, they would actually see the impressivewebs.com home page. For example, if you visited peanutbuttersandwich.animationfillcode.com, you would see the impressivewebs.com home page with the animationfillcode.com URL still in the address bar.

Not exactly something that someone would be likely to stumble across, nor is it an extremely urgent issue, but I think it should be fixed. So in this post I’ll be straying pretty far away from my usual front-end development-related posts, and I’ll be documenting, step by step, exactly what I did to fix this problem on my current dedicated-virtual Media Temple plan. Even if this information doesn’t apply to your current hosting plan, it might nonetheless serve as a reminder to get the problem fixed.

Section 1: Log in to Plesk and Add a New Subdomain

The steps in each of these sections prior to Section 5 are to be done for all non-primary domains in your (dv) hosting plan. For your primary domain, you’ll fix the subdomain problem using .htaccess (see Section 5 below).

First go to your Media Temple account center and log in. To the right of your domain list you should see the “Plesk” login button. Click that button and log in to Plesk with the necessary credentials.

Log in to Plesk

Once into Plesk, click the “domains’ link in the left sidebar:

Click Domains in sidebar

That will bring up a list of your domains. In there, choose any of the “control panel” options to the right of your domains.

Open the domain control panel

From what I can tell, it doesn’t seem to matter which one of these control panel links you choose. It looks like they all just take you to the same basic “control panel” for all your domains. If anyone wants to correct me on that, please do.

Once inside your control panel, click on the “Websites & Domains” tab along the top navigation:

Open Websites & Domains

Once that page opens, you’ll see a list of your domains at the bottom of the page. Above that list you’ll see a link labelled “Add New Subdomain”. Choose that option:

Add a new subdomain

You’ll then be presented with this screen:

The new subdomain screen

This is where we’ll define a wildcard subdomain that will redirect to the primary domain. But the good thing is, this will not affect any real, working subdomains that you might have set up; this will only redirect random non-existent subdomains, and this will also help solve the problem of non-primary domains redirecting to the primary domain on the account.

Section 2: Define Your Wildcard Subdomains for Each Domain

On the “add new subdomain” page, you’ll want to fill in the info to define how to handle the wildcard subdomains. First, for the subdomain “name”, you have to choose a name that will definitely be listed last in a list of named subdomains. Media Temple’s support staff recommended “zz-wildcard”, so that’s what I chose.

Choose a wildcard subdomain name

Next, you want to make sure to select the correct domain in the drop-down list of domain names for your account. I would assume you’ll be fixing all domains, so in that case, you’ll have to repeat this section for each of the domains you want to fix. Just make sure you don’t inadvertently leave your primary domain as the chosen domain, because that will produce incorrect and possibly harmful results.

Not for the primary domain

Finally, the screen presents you with an option to fill in called “Document root”, also referred to here as the website’s “home directory”. In this option, you want to fill in the exact name of the folder where your files are located for the selected domain. On Media Temple’s (dv) plan, this home directory name was set up when you set up the domain. For my own plan, unfortunately, I had set up the home directories in a non-standard way, so it was a little more complicated for me (See Section 6 below). But for most cases, it should just be a matter of putting in the original home directory name.

Once you fill in the correct info, click “OK” to create the subdomain.

Section 3: Log in With Root Access and Create a vhost.conf File

Now it gets a little more tricky. For those with little command-line experience, it’s a bit challenging. I do some of my command line stuff using PuTTY. Whatever you choose, you need to log in to your server with root access. Evidently you can also do this type of thing via FTP, but the settings in your FTP client are a little different.

Once you’ve logged in, navigate to the home directory of the domain you’re currently fixing (the one you selected when you created the wildcard subdomain in the previous section). In my case, this would mean navigating to:

/var/www/vhosts/selecteddomain.com/subdomains/zz-wildcard/conf

In this example, “selecteddomain.com” would be the name of the home directory that matches the domain you’re fixing. That directory should be empty. In there you want to create a vhosts.conf file. In PuTTY, I do this by typing:

vi vhost.conf

This creates a file called “vhost.conf” and opens it in a text editor in PuTTY. To start editing the empty file, type the letter “a” on the keyboard. This allows you to “INSERT” text into the file. In this file, you then type the following:

ServerAlias *.selecteddomain.com

Where, once again, you would replace the domain name with the domain name you’re dealing with. Once you’ve added this line to the vhost.conf file, hit “ESC” on your keyboard to stop editing the file. To save the file, type the following in PuTTY:

:w

And then hit enter. To exit the editor, you can use ctrl-z or type “:q” (quit). Finally, you need to restart the server so the new changes take effect. I did this using the following command:

/usr/local/psa/admin/sbin/websrvmng -a -v

I believe there are other ways to do this, and I think you’d have the same effect if you just restarted the server from your Media Temple Account Center, but either way this seems to be a necessary final step to get the new configuration to take effect.

Section 4: Repeat for Each Domain

All the steps outlined above after you click on “control panel” need to be repeated for each domain that you want to fix. Just make sure you select the correct domain in the “Add New subdomain” section, and that you type in the correct home directory.

Also, for each domain, you have to navigate with root access to the respective “zz-wildcard” folder (or whatever you chose to call it), and create a new “vhost.conf” file with the configuration info specific to that domain.

The only domain that you don’t do this for is your primary domain.

Section 5: Fix the Primary Domain

Once you’ve corrected the wildcard subdomain issue on all your secondary domains, you’ll also need to do this with your primary domain. I don’t know squat about .htaccess stuff. Any .htaccess-related code that I ever use will be stuff I find through search.

Fortunately, Media Temple’s staff go above and beyond the call of duty, and one of their techs actually wrote a mod rewrite rule into my .htaccess file to get the subdomain problem fixed on my primary domain. Here’s the code:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{HTTP_HOST} !^www.impressivewebs.com$ [NC]
   RewriteRule ^(.*)$ http://www.impressivewebs.com/$1 [L,R=301]
</IfModule>
Update (March 25, 2012): As pointed out in the comments, originally this .htaccess rule shown above would not redirect something like “whatever.www.impressivewebs.com”. Adding the caret character (^) seems to fix this problem.

And that’s it. Now, if anyone tries to visit a random, non-existent subdomain on www.impressivewebs.com, they’ll just get redirected to the same page with the random subdomain replaced with “www”. Of course, if your domain doesn’t use “www” then you would need a different rewrite rule. All the best with that. :)

Section 6: My Non-Standard Setup

In my case, for some reason, I had set up my other domains as sub-folders of the primary domain. So the home directories were a bit weird and thus the wildcard thing didn’t quite work as expected. But once again, Media Temple’s staff went above and beyond and were able to fix the problem for me.

Basically, since my home directories were all located within my primary domain’s home directory, for each of these secondary home directories, I had to choose “z-selecteddomain” as the “document root” (See the last part of Section 2 above). Then, after creating the subdomain in Plesk, I created an .htaccess file in the new folder with the following rewrite rule:

Redirect 301 / http://selecteddomain.com

This gets done for each domain (except primary). Also the “z-selecteddomain” document root folder could be anything; this name was chosen by the tech to help group them together at the bottom of the folders list.

I really have no idea why my sub folders were configured in this way (it’s not a wrong setup, it’s just unconventional), but this redirect helped iron things out so that the wildcard subdomains were pointing to the correct location.

Conclusion

I’m obviously not a server admin, so what I’ve written above is just a superficial step-by-step reconstruction of what I did to solve this problem.

One of the benefits to having no random wildcard subdomains is the problem of duplicate content for SEO purposes. As it was before, theoretically someone could have linked to any one of my pages using a random subdomain, and if Google indexed the page in that state, it could have created a duplicate content problem. Not that you would necessarily be penalized for such a thing, but I suppose PageRank or overall backlink juice would be split if that were the case.

I also have a few client websites hosted on my account, so imagine how the client would have reacted if they had typed a random subdomain in front of their URL and saw the home page for impressivewebs.com. Not very professional looking, so even though it’s extremely unlikely anyone would notice such a thing, it’s still something that should be fixed.

And of course, if anyone has anything to add or correct, or knows of a way to do this purely with .htaccess (which I don’t think is possible, but who knows?), please offer your feedback.

Advertise Here

15 Responses

  1. Great write up! We have a (mt) Wiki article for the same, but yours is much moe thorough. The (mt) Wiki is heavily maintained by the community and I encourage you to consider contributing to the existing article:

    http://wiki.mediatemple.net/w/%28dv%29:Configure_a_wildcard_subdomain

    Also, thank you very much for the kind mention about (mt)’s support.
    Keep up the good work!

    -(mt) Sara

    • Hey, Sara. I was meaning to link to that article in my post but, as usual, in the rush to get it written, forgot. :)

      Anyhow, I’m glad you found it accurate and useful. If I get a chance, I’ll try to contribute to that article, but feel free to link to this one in the Wiki if that helps.

    • That link got deleted :( … Too bad they think we all have the plesk 10.4+, i guess i have no other easier option than to follow your steps for all my 50+ hosted domains…

      • Adam Mustill:

        heckur,

        If you have 50+ domains, I would certainly take a look at my original comment below for a quicker, automated solution which only requires setting up one subdomain.

        A.

  2. Your solution is inaccurate and will not work how you think it will. The rule in your .htaccess file will allow for someone to link http://xxxwww.impressivewebs.com or http://whatever.www.impressivewebs.com, http://anything.fwww.impressivewebs.com etc. which defeats the purpose of the solution in the first place.

    You should use the caret character to signal the start of the regex pattern or else it will just allow anything that matches (.*)www.impressivewebs.com, so for your example instead of this:
    RewriteCond %{HTTP_HOST} !www.impressivewebs.com$ [NC]
    You should just use this:
    RewriteCond %{HTTP_HOST} !^www.impressivewebs.com$ [NC]

    Please take more care to actually test solutions before advocating them to people who don’t know better.

    • Whoever you are, you obviously have something valuable to share. So why not use your real name and be nice about it? I make *tons* of mistakes on my site. I publish whatever I learn, regardless of whether it’s perfect or not. That’s how I learn more.

      Also, although you’re correct, what you’re demonstrating has a microscopic chance of even being a problem. Considering that neither the Media Temple employee that wrote this code, or the one that commented above even noticed that problem, it’s obviously not as obvious as you think it is.

      • Nunya Bidness:

        Thank you for updating your article. I appologise for my manner, I am a straight talking person who takes my craft seriously and I value my privacy.

        I was lead here by someone who cited your article and was puzzled as to why even though they followed the instructions to the letter, they had duplicate content flagged in Google and wanted my help. I meant no offense.

        I have to disagree that it is not a big issue as there are many cases on the internet where input of a domain into a form of some sort will be regexed and turned into a URL (you even do something similar here in your comments section), all it takes is one typo in the wrong place for Google to follow (remember Google will also crawl rel=”nofollow” links, just not share PageRank).

        Thanks again for updating, glad I could help.

        • No problem, I understand. I hope I wasn’t too harsh. :)

          The important thing is, you caught the glitch and now it’s fixed. Thanks for your help.

    • I’ve fixed this problem now.

      Another thing to note is that this was only happening on my primary domain, not any secondary domains in the same account. So without changing anything, this works fine:

      http://xxxwww.animationfillcode.com

  3. Adam Mustill:

    Nice article and solution. It’s one of very few I found whilst researching this issue myself for my own (mt) set up.

    However, I ultimately took a different approach to eliminate having to set up a subdomain for each domain, and to automate it for any future domains.

    I decided to create one subdomain (wildcard.domain.com) to handle all unknown/wildcard requests by setting that domain as my default domain for the IP in Plesk. This way stupidrequest.domain.com and any other unknown request for any other domain on my server would point there.

    Then, once all unknown requests were pointing to this subdomain, I simply created a small PHP script to remove the subdomain from the request and redirect to the parent domain.

    
    <?php
    
    /* ========================================
    
       This script handles the wildcards on all
       domains by extracting the parent domain
       and redirecting to it.
    
    ========================================= */
    
    $bits = explode('.', $_SERVER['HTTP_HOST']);
    $domain = implode('.', array_slice($bits, 1));
    
    header( (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1') . ' 301 Moved Permanently');
    header('Location: http://' . $domain);
    exit;
    ?>
    

    If multiple subdomains are requested, eg. my.stupid.request.domain.com, only the first subdomain is removed resulting in three redirects. This may not be ideal, but you have to consider that these types of requests will be supremely rare, if ever.

    • Very interesting, Adam. That definitely looks easier. I’ll have to consider maybe if I should do that, too, so I don’t have to go through these steps for each new domain.

      Thanks!

      • Adam Mustill:

        Thanks. I thought it was worth contributing as a different perspective. Using PHP for something that ultimately the server should be able to handle is a little hacky, but it’s a working and future-proofed solution.

        • Ben:

          Hey Adam, just found your solution here and used it on my own (dv) server. It works great. Thanks for this!

  4. You have GOT to be kidding me. The PLESK solution was so simple, I’m crying tears of joy. I’ve been wrestling around with lame hand-editing of .htaccess, symlink & mod_rewrite solutions so long, upgrading from one hosting environment to the next-upgraded-version, trying to get this to work right that when the wildcard redirect worked perfectly and instantly, I had absolutely no idea what I was looking at, what I was supposed to be looking at, or what had happened. I had completely forgotten what this would look like when it finally worked. THANK GOD for generous, helpful bloggers like you. And the WYSIWYG blog comment is pretty cool, too.

    I’m using PLESK Panel 11.0.9 Update #58 September 1, 2013… and it actually has an option for wildcard subdomains using (asterisk) and says as much in the UI. Is that why it works nicely without vhost and mod_rewrite magic??? This seems altogether TOO SIMPLE.

    Am I missing something vital??? (I happen to WANT it to display the subdomain, as typed, in my visitors address bar).

    • Daniel, you should learn to express your emotions! lol… just kidding…

      But seriously, I’m glad this helped you. As for your last comment, I’m not sure why you would want it to display the subdomain, even after it redirects…. If that’s the case, then I don’t think you can do this through Plesk. You’d probably have to use mod_rewrite/htaccess and all that other stuff you love. :)

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.