Mod-Rewrite

如何將子域重定向到以子域為參數的域

  • December 10, 2016

我想將我的萬用字元子域重定向到我的主域,使用子域作為 URL 中的 GET 參數,使用.htaccess.

我想發生的事情的例子:

billy.example.com

重定向到

www.example.com/profile?user_name=billy

這是我根據本網站上的其他答案匯總的目前規則:

RewriteCond %{HTTP_HOST} ^(.*).example.com
RewriteRule ^(.*)$ http://www.example.com/shop?user_name=%1 [R,L]

但是,當重定向發生時,我得到以下 URL 並出現“重定向循環”錯誤:

www.example.com/profile?user_name=www

我在這個網站上看到了這幾種不同的方法,但不幸的是,它們都不適合我。

(我使用的是 PHP,並且*在我的託管面板中設置為子域。)

在嘗試使用 .htaccess 解決此問題但失敗後,我最終使用 PHP 為我進行 URL 解析。對於那些想看看我做了什麼的人:

$host = $_SERVER['HTTP_HOST'];
$subdomain = str_replace('.example.com', '', $host);
if($subdomain != 'www')
header("位置:http://www.example.com/shop?user_name=".$subdomain);

您的重定向循環正在發生,因為您正在重定向所有內容(甚至是 www.example.com)。也許嘗試類似:

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.example\.com$ [NC]
RewriteRule ^/(.*)$ http://www.example.com/shop?user=%1 [L,R=301]

這應該只在您使用www.example.com以外的東西時觸發。

引用自:https://serverfault.com/questions/66894