Search code examples
apachemod-rewritesubdomain

How to rewrite subdomain and subsubdomain into a parameter?


Can anyone please help with the following rewrite for apache?

Imagine I have the domain domain.com

What I want:

If people request www.domain.com then return www.domain.com (ie index.php in my root directory)

If people request subA.subB.domain.com then return www.domain.com?sub=subA.subB

If people request sub.domain.com then return www.domain.com?sub=sub

If people request domain.com then return www.domain.com

I know the rule here is to work on it yourself. I have. For example, the similar question here asks to redirect to /subA/subB - but even if I understood that answer I would not know how to adapt it to what I need, which is ?sub=subA.subB . I have tried to understand rewrite many times over the years. Ok, /sobstory -off.


Solution

  • This will rewrite your subdomains:

    RewriteEngine on
    RewriteCond %{QUERY_STRING} !^sub=
    RewriteCond %{HTTP_HOST} ^(?!www\.)(.+)\.domain\.com$
    RewriteRule ^(/?)$ $1?sub=%1
    

    Replace the domain as appropriate. Make sure each . has a slash before it as it does now.

    It will only work for the index page. If you want it to work when there is something after domain.com/ let me know.

    As for making http://domain.com work, I suggest redirecting that to www.domain.com so you don't get duplicate content issues from search engines. Do that with this (add it below the above):

    RewriteCond %{HTTP_HOST} =domain.com
    RewriteRule ^ http://www.domain.com%{REQUEST_URI} [R=301,L]
    

    No need for the slashes before the dots on that one.

    Let me know if any of that is no good for you.


    Original poster's postscript based on comments:

    The above solution is correct for the question but assumes the following configurations on the server:

    • The subdomain *.domain.com has been added and points to the document root for the site
    • An 'A record' for *.domain.com has been configured in the DNS configuration and points to the IP address of the server