You can't "rewrite" a URL across different hostnames (you would need to implement a reverse proxy) and I assume a "redirect" is undesirable.
However, if the subdomains and main domain all point to the same area of the filesystem then you don't need to change the hostname/domain. A ordinary rewrite (on the same host) is all that's required.
To check the subdomain on the requested host, you need a condition (RewriteCond
directive) that checks against the HTTP_HOST
server variable (ie. the value of the Host
HTTP request header). The RewriteRule
pattern matches against the URL-path part of the URL only.
For example:
RewriteEngine On
RewriteCond %{QUERY_STRING} !^country=
RewriteCond %{HTTP_HOST} ^(us|eg)\.example\.com [NC]
RewriteRule ^ /?country=%1 [L]
As noted above, this assumes the subdomains and main domain point to the same area of the filesystem. This is common on a system where all requests are managed by a single CMS. (And you aren't making any attempt to change the hostname in your example directives.)
The %1
backreference holds the subdomain ("us" or "eg" in this example) from the requested hostname.
The additional condition that checks the query string for the absence of the country=
URL parameter is to prevent a rewrite loop.
However, you've not stated anything about the URL-path? And you should be rewriting directly to the file that is handling the request (index.php
?). In its current state, the above "rewrite" is reliant on mod_dir making an additional subrequest for the DirectoryIndex.
RewriteRule (US|EG) ?c=$1 [NC , L]
RewriteRule :\/\/(.*?).example.com ?C=$1 [NC , L]
There are numerous errors with these directives:
- You say you've tried these, however, the erroneous spaces in the flags argument will result in an immediate 500 Internal Server Error when the file is first parsed.
- As mentioned above, the
RewriteRule
pattern (first argument) matches against the URL-path only. This does not include the hostname.
- The regex in #1 is far too general and matches "US" or "EG" anywhere.
- In order to match against an absolute URL (as you appear to be trying to do in the second example) then you would need to match against
THE_REQUEST
server variable (which contains the first line of the request headers, include the request method).