2013-08-18 105 views
6

期望的結果:的.htaccess重寫:子域中GET var和路徑GET變種

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 

通過的.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] 

我很難結合這兩個...任何指針,請?

編輯
意外行爲我現在經歷的是,如果我有一個子域後的.com /路徑,只有子域名會被通過,即:

http://hello.example.com/world-> index.php?subdomain=hello 
+0

http://stackoverflow.com/questions/25582265/mod-rewrite-setting-subdomain-and-directory-to-get-variable – shaunw

+0

如果您將VirtualHosts用於處理子域名,而.htaccess處理url改寫。兩年之後,你如何解決這個問題? –

回答

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] 

第二條規則需要QSA標誌,否則第一條規則的查詢字符串會丟失。

+0

啊,'查詢字符串追加',有趣!非常豐富,謝謝。 –

+0

你好喬恩林​​如何重寫像http://admin.example.com/ - > http://example.com/admin/ – SKG

+0

上面的代碼似乎不適用於OP的最後一個例子(http:// hello.example.com/world/test)。它將在'path ='var中以'/ world/test/test'重複第二段(/ test)兩次。 – shaunw