[英]Changing base URL on part of a page only
我的網站上有一個頁面,它從同一服務器上的另一個(舊版)站點的數據庫中獲取並顯示新聞項目。 某些項目包含應修復的相對鏈接 ,以便它們指向外部站點,而不是在主站點上導致404錯誤。
我首先考慮在獲取的新聞項目上使用<base>
標簽,但這會改變整個頁面的基本URL,打破主導航中的相對鏈接 - 而且它也感覺非常hackish。
我目前正在考慮創建一個正則表達式來查找相對URL(它們都以/index.php?
)並在它們前面加上所需的基本URL。 還有更優雅的解決方案嗎? 該站點基於Symfony 2構建並使用jQuery。
以下是我將如何解決這個問題:
function prepend_url ($prefix, $path) {
// Prepend $prefix to $path if $path is not a full URL
$parts = parse_url($path);
return empty($parts['scheme']) ? rtrim($prefix, '/').'/'.ltrim($path, '/') : $path;
}
// The URL scheme and domain name of the other site
$otherDomain = 'http://othersite.tld';
// Create a DOM object
$dom = new DOMDocument('1.0');
$dom->loadHTML($inHtml); // $inHtml is an HTML string obtained from the database
// Create an XPath object
$xpath = new DOMXPath($dom);
// Find candidate nodes
$nodesToInspect = $xpath->query('//*[@src or @href]');
// Loop candidate nodes and update attributes
foreach ($nodesToInspect as $node) {
if ($node->hasAttribute('src')) {
$node->setAttribute('src', prepend_url($otherDomain, $node->getAttribute('src')));
}
if ($node->hasAttribute('href')) {
$node->setAttribute('href', prepend_url($otherDomain, $node->getAttribute('href')));
}
}
// Find all nodes to export
$nodesToExport = $xpath->query('/html/body/*');
// Iterate and stringify them
$outHtml = '';
foreach ($nodesToExport as $node) {
$outHtml .= $node->C14N();
}
// $outHtml now contains the "fixed" HTML as a string
您可以通過將http:\\\\
放在鏈接前面來覆蓋base
標記。 也就是說,提供一個完整的URL,而不是相對的URL。
好吧,實際上不是解決方案,但主要是小費......
您可以開始使用ExceptionController進行播放。
在那里, 例如 ,您可以尋找404錯誤並檢查附加請求的查詢字符串:
$request = $this->container->get('request');
....
if (404 === $exception->getStatusCode()) {
$query = $request->server->get('QUERY_STRING');
//...handle your logic
}
另一種解決方案是使用其控制器為此目的定義特殊路由,這將捕獲對index.php
請求並執行重定向等。 只需在路由requirements
中定義index.php
,然后在路由頂部移動此路由。
不是最清楚的答案,但至少我希望我給你一個方向......
干杯;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.