.htaccess重写:子域为GET var,路径为GET var

Ben*_*n Y 7 php apache .htaccess mod-rewrite

期望的结果:

http://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://example.com/world            -> index.php?path=world
http://example.com/world/test       -> index.php?path=world/test
http://hello.example.com/world/test -> index.php?subdomain=hello&path=world/test
Run Code Online (Sandbox Code Playgroud)

使用我现在拥有的.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 ^.*$ index.php?subdomain=%1

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

我很难把两者结合起来......请指点一下?

编辑
我现在遇到的不需要的行为是,如果我有一个子域和.com /之后的路径,只有子域将被传递,即:

http://hello.example.com/world-> index.php?subdomain=hello
Run Code Online (Sandbox Code Playgroud)

Jon*_*Lin 7

使用第一个规则添加subdomain参数,而不更改URI,然后使用第二个规则将URI路由到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} !-f
RewriteCond %{HTTP_HOST}        !^www
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?path=$1 [L,QSA] 
Run Code Online (Sandbox Code Playgroud)

第二个规则需要QSA标志,否则第一个规则的查询字符串会丢失.