Apache mod_rewrite ANY subdomain(s) to root domain

2019-06-02 00:04发布

Say you've got an Apache2 virtual host setup, something like this:

/htdocs/parent1.com
/htdocs/sub1.parent1.com
/htdocs/sub2.parent1.com
/htdocs/parent2.net
/htdocs/parentn.org

Say you'd like to do this with VirtualDocumentRoot /htdocs/%0, so that you can add and remove virtual hosts without tinkering with your Apache configuration. That's important: please please no messing with htaccess files or httpd.conf every time a virtual host comes or goes - whether that host is a parent domain or not. In fact, say you're using AllowOverride None.

Anyway, the question is, how might you 301 redirect non-existent sub-domains to their corresponding parent domains without redirecting existent sub-domains?

1条回答
来,给爷笑一个
2楼-- · 2019-06-02 00:29

I may have solved my own problem. However I would appreciate any feedback if somebody finds a problem with what I'm doing.

The following leaves alone any request to an arbitrary subdomain, as long as there exists a corresponding document root; but redirects any request to a subdomain which does not exist in the filesystem.

<IfModule rewrite_module>
    RewriteEngine On
    RewriteMap lowercase int:tolower
    RewriteCond "/htdocs/${lowercase:%{HTTP_HOST}}" !-d
    RewriteCond %{HTTP_HOST} "\.([^\.]+\.[^\.]+)$"
    RewriteRule ^/(.*)$ "http://%1/$1" [R=301]
</IfModule>

Allows me to setup wildcard DNS and use name-based virtual hosting, without touching any configuration settings. Also, there's no htaccess involved. Just make your folder with any name like "/htdocs/[host.]domain.tld" and you're up and running. As far as I can tell, this doesn't really work with SSL/TLS (presumably something to do with %{HTTP_HOST}?), but secure sites are comparably few and better resolved by IP address than by hostname.

查看更多
登录 后发表回答