I'm trying to redirect a subdomain to a subfolder e.g. forums.domain.com to www.domain.com/forums

Note that I started the forums in the subfolder format but worried that members might mistakenly try to access the forums using the subdomain format.

RewriteCond %{HTTP_HOST} ^(www\.)?forums\.domain\.com
RewriteRule .* /forums [L]

From what I read the codes above should work through .htaccess, but do I still need to create a DNS A record to point to the IP address of the server?

  • I manage to get the redirection working by adding a DNS A record but now the url becomes forums.domain.com. How can I change my htaccess so that it retains the url as www.domain.com/forums?
    – Laurent Ho
    May 7 '11 at 8:30

Try this:

Options +FollowSymLinks 
RewriteEngine on
RewriteCond %{HTTP_HOST} !^(www)\. [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com [NC]
RewriteRule (.*) http://www.domain.com/%1 [R=301,L]

This is generic and will redirect all subdomains to a subdirectory. If you have only one subdomain you want to redirect you can hardcode it in.

  • @John: I've been searching for months on how to do this successfully. So far your snippet of code is the only one that has worked on my WP subfolder multisite install. I think it might have something to do with the "+FollowSymLinks" line. What I wanted to do was take xyz.domain.com and redirect to domain.com/**xyz**. That works with the above code. But I'd like abc.domain.com to redirect to domain.com/**xyz** as well (i.e., two subdomains pointing to the same subfolder). How exactly do I do that? Despite my layman's attempts to "reverse engineer" or adapt your code, I don't understand
    – user19790
    Nov 8 '12 at 19:37
  • I also have tried multiple versions of what you have, from other sources though, with no luck. Yours was the only which did in fact work for me (at least on MAMP.) The only difference that I can see is that you are using %1 vs $1. John, would you mind explaining a little bit about that? Thanks!
    – Natetronn
    Jun 26 '13 at 22:07
  • @John This works perfectly. How to keep the subdomain active instead of the folder in the url? Thanks
    – Vins
    Apr 27 '20 at 15:33

Without having to specify a domain in the circumstance that multiple domains point to the website root or that a production .htaccess rules can be applied to:

RewriteCond %{HTTP_HOST} ^(.*)\.ANYdomain\.com [NC]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.