.htaccess重写:子域名为GET参数,文件路径后域名完整

时间:2014-08-19 16:59:13

标签: apache .htaccess mod-rewrite url-rewriting

我想使用htaccess将子域重写为get paramater但保留域之后的所有内容+将参数添加到end或url。

期望的结果:

http://mpmain.example.com/          -> index.php
http://www.example.com/             -> index.php
http://hello.example.com/           -> index.php?subdomain=hello
http://whatever.example.com/        -> index.php?subdomain=whatever
http://whatever.example.com/index.php?page=login -> index.php?page=login&subdomain=whatever
http://whatever.example.com/index.php?page=about&action=help -> index.php?page=about&action=help&subdomain=whatever

使用我现在拥有的.htaccess,我可以使用以下代码实现子域到参数(index.php?subdomain = whatever)映射。

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}        !^mpmain
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /$1?subdomain=%1

在下面添加了第二次重写,但这个不起作用。我如何调整它以获得理想的结果?

# Map all requests to the 'path' get variable in index.php
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?subdomain=$1 [L,QSA]

我从.htaccess rewrite: subdomain as GET var and path as GET var

获取了代码

1 个答案:

答案 0 :(得分:4)

您可以在root .htaccess中使用此代码:

DirectoryIndex index.php
RewriteEngine On

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