简体   繁体   中英

wildcard subdomain in .htaccess

I want to make a simple page which is available with any (wildcard) subdomain.

For example, you visit hello.domain2.com and the page will echo the name of the subdomain "hello". Also the URL has to stay "hello.domain2.com". This shouldn't be too hard, but since my host has multiple domains in 1 root I'll have to tweak my .htaccess file.

When I check out the htaccess, the host has automaticly made the following rules:

RewriteEngine on    

RewriteCond %{HTTP_HOST}    ^www.domain1.com$
RewriteCond %{REQUEST_URI}  !^/domain1.com/
RewriteRule (.*)            /domain1.com/$1 [last]
RewriteCond %{HTTP_HOST}    ^domain1.com$
RewriteCond %{REQUEST_URI}  !^/domain1.com/
RewriteRule (.*)            /domain1.com/$1 [last]

RewriteCond %{HTTP_HOST}    ^www.domain2.com$
RewriteCond %{REQUEST_URI}  !^/domain2.com/
RewriteRule (.*)            /domain2.com/$1 [last]
RewriteCond %{HTTP_HOST}    ^domain2.com$
RewriteCond %{REQUEST_URI}  !^/domain2.com/
RewriteRule (.*)            /domain2.com/$1 [last]

RewriteCond %{HTTP_HOST}    ^www.domain3.com$
RewriteCond %{REQUEST_URI}  !^/domain3.com/
RewriteRule (.*)            /domain3.com/$1 [last]
RewriteCond %{HTTP_HOST}    ^domain3.com$
RewriteCond %{REQUEST_URI}  !^/domain3.com/
RewriteRule (.*)            /domain3.com/$1 [last]

So far I've configured the server to accept any subdomain for my domain2.com, but my host redirects all the subdomains to my root folder.

How can I make the wildcard subdomains go to /domain2.com instead?

You could exchange the domain2 rule block for:

RewriteCond %{HTTP_HOST}    ^([\w-]+).domain2.com$
RewriteCond %{REQUEST_URI}  !^/domain2.com/
RewriteRule ^(.*)$          /domain2.com/$1?subdomain=%1 [LAST,QSA]

The ([\\w-]+) is a wildcard for server names, and the %1 can be used as placeholder in later RewriteRules. (The second RewriteCond could also be turned into an assertion..)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM