.htaccess 重写子域作为请求参数

.htaccess rewrite subdomain as request parameter

Ho 我可以重写此请求类型:

http://name1.domain1.com/        -> index.php?subdomain=name1
http://name2.domain2.org/        -> index.php?subdomain=name2

我需要在 php 脚本 ( index.php ) 中管理子域 GET 变量。 我需要所有域的通用规则。

这是我的 .htaccess 文件,但它不起作用。

RewriteEngine On

# Parse the subdomain as a variable we can access in PHP, and
# run the main index.php script
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /?subdomain=%1

谢谢。

假设您正在使用 PHP。您不需要将其作为查询参数,因为从 PHP 您已经可以看到哪个是客户端浏览器请求的 URL。

echo $_SERVER['HTTP_HOST']

输出:

bubbles.domain.com

你只需要解析它。

$host= (explode( '.', $_SERVER['HTTP_HOST']))[0];
$subdomain = $host[0];

if($subdomain == 'www' || $subdomain == 'www2') 
    $subdomain = $host[1];

echo $subdomain;

输出:

bubbles