Apache mod_rewrite ANY subdomain(s) to root domain, unless existent as virtualdocumentroot

怎甘沉沦 提交于 2019-12-08 04:50:00

问题


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:


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.



来源:https://stackoverflow.com/questions/11324539/apache-mod-rewrite-any-subdomains-to-root-domain-unless-existent-as-virtualdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!