![](/img/trans.png)
[英]Redirect visitor to different domain based on the domain and page they came from
[英]Best way to detect if request came from a different domain or a sub domain
我正在構建一個使用子域和自定義域名的應用程序,這些域名位於數據庫中供用戶使用,因此如果請求來自另一個域,我將從數據庫中檢查該自定義URL是否確實存在或請求來自何處一個子域名,我會檢查是否存在。 如果是我做我的東西。
考慮一下我正在尋找的一個簡單例子:
if(is_user_request())
{
$url = get_url();
// assuming that get_url() magically decides whether to output ..
// a custom domain (http://domain.tld)
// or a subdomain's first part (eg. "this".domain.tld)
}
else
{
// otherwise it's not a sub domain nor a custom domain,
// so we're dealing with our own main site.
}
在你開始之前假設因為我有0個代表,我在這里要求“teh代碼”。 我有一個完全工作的方式,這是以下內容:
// hosts
$hosts = explode('.', $_SERVER['HTTP_HOST']);
// if there is a subdomain and that's under our $sitename
if(!empty($hosts[1]) AND $hosts[1] === Config::get('domain_mid_name'))
{
$url = $hosts[0];
$url_custom = false;
}
// if there is no subdomain, but the domain is our $sitename
elseif(!empty($hosts[0]) AND $hosts[0] === Config::get('domain_mid_name') AND !empty($hosts[1]) AND $hosts[1] !== Config::get('domain_mid_name'))
{
$url = false;
$url_custom = false;
}
// otherwise it's most likely that the request
// came from a entirely different domain name.
// which means it's probably $custom_site
else
{
$url = false;
$url_custom = implode('.', $hosts);
}
if($url)
{
return $url;
}
if($url_custom)
{
return $url_custom;
}
但是,我確信有更好的方法可以做到這一點。 因為首先,HTTP_HOST不包含'http://',所以我需要手動添加它,我很確定這整個if,否則只是一個矯枉過正。 所以,比我聰明的人,請賜教。
哦,不,我沒有預定義的子域名。 我設置了一個簡單的通配符* .domain.tld,所以所有子域都轉到主腳本。 我只是這樣說,因為從我搜索解決方案中我發現了許多答案,建議手動創建一個子域,這甚至與我所要求的內容沒有太大關系,所以讓我們跳過這個主題。
除非您想將Web服務器中的不同參數傳遞給PHP,否則$_SERVER['HTTP_HOST']
是正確的方法。
至於協議,請注意請求協議應由$_SERVER['HTTPS']
確定,而不是假設它是http
。
要提取子域,您可以使用array_shift
然后運行
$subdomain = array_shift(explode('.', $_SERVER['HTTP_HOST']));
但一般來說,你所擁有的是如何做到的。
如前所述, $_SERVER['HTTP_HOST']
是要走的路。
但是代碼中存在錯誤。 您假設發送的主機名由2或3個組件組成,但您無法確定。 你至少應該檢查count($hosts)
。
如果您通過示例將domain.tld用於您自己的網站,那么您最好首先檢查是否已發送domain.tld
(您快速返回頁面); 然后查看substr($_SERVER['HTTP_HOST']...,-11)==='.domain.tld'
,若然,返回子網站(適用於任何級別的子域,仍然很快); 否則錯誤恢復,因為已將完全外來域路由到您。 需要注意的關鍵是,層次結構頂部的域匹配意味着匹配右對齊的主機名字符串:
.domain.tld | subsite-pattern
sub12.domain.tld | MATCH
sub12.dumain.tld | NO MATCH
sub12domain.tld | NO MATCH
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.