[英]Symfony2 / Twig : Generate Alternate Absolute URL Path for use with CDN?
[英]Generate absolute URL with specific scheme in Symfony2
我想在 Symfony2 控制器中生成一個具有特定方案 (https) 的絕對 URL。 我找到的所有解決方案都指向我配置目標路由,以便它需要該方案。 但是我需要該路由在 http 中保持可訪問性,所以我不能將它設置為需要 https(在這種情況下,http 請求被重定向到相應的 https URL)。
有沒有辦法生成一個 URL,在該 URL 生成的范圍內,一個特定的方案?
我看到使用'network'
關鍵字會生成一個“網絡路徑”樣式的 URL,它看起來像“//example.com/dir/file”; 所以也許我可以簡單地做
'https:' . $this->generateUrl($routeName, $parameters, 'network')
但我不知道這對於任何路由或請求上下文是否足夠健壯。
更新:在對 URL 生成代碼進行調查后,這種“網絡路徑”解決方法似乎完全可靠。 網絡路徑完全作為絕對 URL 生成,在“//”之前沒有方案。
最好的方式去這個
$url = 'https:'.$this->generateUrl($routeName, $parameters, UrlGeneratorInterface::NETWORK_PATH)
根據代碼或文檔,目前您無法在 generateUrl 方法中執行此操作。 所以你的“hackish”解決方案仍然是最好的,但正如@RaymondNijland評論的那樣,你最好使用str_replace
:
$url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters));
如果你想確保它只在字符串的開頭改變,你可以寫:
$url = preg_replace('/^http:/', 'https:', $this->generateUrl($routeName, $parameters));
不,冒號 ( :
) 在正則表達式中沒有特殊含義,因此您不必轉義它。
使用默認的UrlGenerator
,如果您不想弄亂字符串,我認為這是不可能的。
你可以讓你自己的HttpsUrlGenerator extends UrlGenerator
引入一個細微的變化:
在方法generate()
,而不是:
return $this->doGenerate(
$compiledRoute->getVariables(),
$route->getDefaults(),
$route->getRequirements(),
$compiledRoute->getTokens(),
$parameters,
$name,
$referenceType,
$compiledRoute->getHostTokens(),
$route->getSchemes()
);
你可以這樣做:
return $this->doGenerate(
$compiledRoute->getVariables(),
$route->getDefaults(),
$route->getRequirements(),
$compiledRoute->getTokens(),
$parameters,
$name,
$referenceType,
$compiledRoute->getHostTokens(),
['https']
);
如您所見, $route->getSchemes()
根據路由設置(您在上面提供的教程鏈接$route->getSchemes()
被注入doGenerate()
) 。
您甚至可以進一步將這個架構數組外部化並通過__construct
提供它。
希望這個對你有幫助 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.