Help with 301 redirect from subdomain to root domain

18,853

To redirect requests for sub.example.com/uri to example.com/uri:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub.example.com$
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

To redirect requests for sub.example.com/uri to example.com:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub.example.com$
RewriteRule ^(.*)$ http://example.com/ [R=301,L]
Share:
18,853

Related videos on Youtube

Lin
Author by

Lin

Updated on September 18, 2022

Comments

  • Lin
    Lin almost 2 years

    I need to forward existing subdomain links to the root domain as the subdomain no longer exists. I have tried so many different lines of code in my .htaccess file and can not get the redirect to work.

    The links to the subdomain look like: http://sub.example.com/dir/y99bb4

    Can anyone suggest any code for me?

  • Lin
    Lin almost 12 years
    Thanks for your reply Nick. I just need to redirect from sub.yourdomain.com/uri to yourdomain.com (no uri)
  • Nick
    Nick almost 12 years
    @Lin Thanks for the information. I've updated my answer with a rewrite rule that drops the path when redirecting.
  • Lin
    Lin almost 12 years
    thanks but it's not working for me. Maybe I'm placing it in the wrong spot in my .htaccess # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On [I tried the code here] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress [I also tried the code here] other working 301s are here I can't seem to format this so it's easy to read.
  • Nick
    Nick almost 12 years
    @Lin I've tested this on a live site and the rules are working for me. Is there still a DNS record for the subdomain in your domain control panel? Or, if you're using nameservers and managing the subdomain with cPanel or similar, is there still a subdomain entry in your cPanel account? Removing either of these will break the redirection because there still needs to be a record that the subdomain existed. Let me know if that's not clear and I'll try to help.
  • Paul Shryock
    Paul Shryock over 5 years
    If I want to use https, would I still use the above code as-is, but with https in the bottom URL, instead of http?
  • Nick
    Nick over 5 years
    @PaulShryock Yes, that would work.