[英]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.