如何在htaccess中获取子域和域

How to get the subdomain and domain in htaccess

比如我有URLsubdomain.example.com.

如何从 .htaccess 中的 URL 中获取 子域

我需要做类似的事情:

RewriteRule (.*) example.com/subdomain/index.php

我找到了 子域 ,但 仍然没有成功。

RewriteCond %{HTTP_HOST} ^(^.*)\.example.com
RewriteRule (.*) example.com/%1/index.php
RewriteCond %{HTTP_HOST} ^(^.*)\.example.com
RewriteRule (.*) example.com/%1/index.php

相同的原则适用于域(尽管您在此处使用的 CondPattern 似乎无效?)。看起来你需要域+TLD(基本上,子域之后的所有内容),所以尝试这样的东西:

RewriteCond %{HTTP_HOST} ^(.+?)\.(.+?)\.?$
RewriteRule ![^/]+/[^/]+/index\.php$ %2/%1/index.php [L]

CondPattern(.+?) 部分获取子域(? 使其非贪婪)。 (.+?) 部分获取域(host 的剩余部分),这也是非贪婪的,以避免匹配完全限定域上的可选尾随点(例如。subdomain.example.com.).

RewriteRule 模式 ![^/]+/[^/]+/index\.php$ 通过仅在 URL 不是以下形式时重写来防止重写循环(500 错误) /<something>/<something>/index.php.