Search code examples
.htaccesshttp-redirectmod-rewritegetsubdomain

.htaccess: Redirect from subdomain to domain with get-request


I'm trying to redirect from m.subsub.subdomain.tld to subsub.subdomain.tld?m=true. So basically, I want to add a GET-request. The existing GETs should stay like they are, so m.subsub.subdomain.tld?abc=def to subsub.subdomain.tld?abc=def&m=true.

I tried the following code but it doesn't work:

RewriteEngine On
ReWriteCond %{HTTP_HOST} m.subsub.subdomain.tld
ReWriteCond %{REQUEST_URI} ^m/
ReWriteRule ^(.*)$ ?=m=true[L]

I tried to understand how the ReWriteCond and ReWriteRule works, but I didn't get that, so I need your help.


Solution

  • ReWriteCond %{HTTP_HOST} m.subsub.subdomain.tld
    ReWriteCond %{REQUEST_URI} ^m/
    ReWriteRule ^(.*)$ ?=m=true[L]
    

    This has a number of issues:

    • The REQUEST_URI holds the URL-path (starting with a slash), so I'm not sure what you are trying to match with ^m/?
    • m.subsub.subdomain.tld - The second argument to the RewriteCond directive is a regular expression. The dots need to be backslash escaped in order to match a literal dot, otherwise it matches any character.
    • You are capturing the URL-path with (.*) - is this required? It's not required in your example. Your example source and target URLs have an empty URL-path.
    • ?=m=true[L] - You have an erroneous = before the m. You are missing a space delimiter before the RewriteRule flags ([L]) - this will be seen as part of the substitution.
    • Since you don't specify a (valid) R flag, or a scheme+hostname, this will result in an internal rewrite, not a redirect.
    • If you want to redirect to a different host, you need to specify this in the substitution.
    • The original query string will be discarded unless you explicitly include the QSA (Query String Append) flag.
    • ReWriteCond and ReWriteRule should be written RewriteCond and RewriteRule respectively. Although that is just convention, it's not an error.

    Try something like the following instead:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^m\.subsub\.subdomain\.tld [NC]
    RewriteRule ^ http://subsub.subdomain.tld?m=true [R=302,QSA,L]
    

    The existing GETs should stay like they are, so m.subsub.subdomain.tld?abc=def to subsub.subdomain.tld?abc=def&m=true

    Note that this will result in the query string being the other way round. ie. the existing query string from the request will be appended, not prefixed onto the new query string. Is that a problem? ie. ?m=true&abc=def, not ?abc=def&m=true.

    This is also a temporary (302) redirect. Change it to 301 (permanent) only when you are sure it's working OK (if this intended to be permanent).