我有我的网站上的网页并获取来自同一服务器上的另一个(传统)网站的数据库显示的新闻项目。 有些物品含有应该是固定的,让他们直接到外部网站 ,而不是导致主网站上的404错误相对链接 。
我第一次使用考虑<base>
上所获取的新闻条目的标签,但是这改变了整个页面的基础URL,打破了主导航相关链接-这感觉相当的hackish了。
目前,我正在想创建一个正则表达式来找到相对URL(它们都与开始的/index.php?
并与所需的基本网址前面加上它们。 是否有此任何更多的优雅的解决方案? 该网站是建立在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
看到它的工作
您可以覆盖base
通过把标签http:\\
在链接的前面。 也就是说,给出一个完整的URL,而不是相对URL。
好吧,实际上不是一个解决方案,但大多是尖...
你可以开始播放aroung与ExceptionController 。
在那里, 只是举例 ,你可以寻求404错误,并检查追加到请求的查询字符串:
$request = $this->container->get('request');
....
if (404 === $exception->getStatusCode()) {
$query = $request->server->get('QUERY_STRING');
//...handle your logic
}
另一种解决方案是定义与它的控制器这样的目的,这将赶上请求特殊航线index.php
和做重定向等等。 只要定义index.php
中requirements
的路线和您的路由的顶部移动这条路线。
不是最清晰的答案永远,但至少我希望我给你一个方向......
干杯;)