我正在尝试为我的网站上的一些PDF和图像文件设置规范链接。
文件夹结构示例:
/index.php
/docs/
file.pdf
/folder1/
file.pdf
/folder2/
file1.pdf
file2.pdf
/img/
sprite.png
/slideshow/
slide1.jpg
slide2.jpg规范URL的示例PDF URL:http://www.example.com/docs/folder1/file.pdf --> http://www.example.com/products/folder1/
我尽量避免将单独的.htaccess文件放入包含我所有图像和PDF的每个子文件夹中。我目前有7个“主”文件夹,每个文件夹都有2-10个子文件夹,大多数子文件夹都有自己的子文件夹。我有大约80个PDF,甚至更多的图像。
我正在寻找一个(半)动态解决方案,其中在某个文件夹中的所有文件将有一个单一的网址标准链接设置。我希望将尽可能多的内容保存在单个.htaccess文件中。
我知道<Files>和<FilesMatch>不能识别路径,<Directory>和<DirectoryMatch>不能在.htaccess文件中工作。
有没有一种相当简单的方法来实现这一点?
发布于 2013-02-08 01:06:23
我不知道单独使用apache规则来解决这个问题的方法,因为它需要某种正则表达式匹配并在指令中重用匹配结果,而这是不可能的。
但是,如果你在其中引入一个php脚本,那就相当简单了:
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|png|pdf)$
RewriteRule (.*) /canonical-header.php?path=$1请注意,这将向脚本发送对所有jpg、png和pdf文件的请求,而不考虑文件夹名。如果只想包含特定的文件夹,可以添加另一个RewriteCond来实现。
现在是canonical-header.php脚本:
<?php
// Checking for the presence of the path variable in the query string allows us to easily 404 any requests that
// come directly to this script, just to be safe.
if (!empty($_GET['path'])) {
// Be sure to add any new file types you want to handle here so the correct content-type header will be sent.
$mimeTypes = array(
'pdf' => 'application/pdf',
'jpg' => 'image/jpeg',
'png' => 'image/png',
);
$path = filter_input(INPUT_GET, 'path', FILTER_SANITIZE_URL);
$file = realpath($path);
$extension = pathinfo($path, PATHINFO_EXTENSION);
$canonicalUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/' . dirname($path);
$type = $mimeTypes[$extension];
// Verify that the file exists and is readable, or send 404
if (is_readable($file)) {
header('Content-Type: ' . $type);
header('Link <' . $canonicalUrl . '>; rel="canonical"');
readfile(realpath($path));
} else {
header('HTTP/1.0 404 Not Found');
echo "File not found";
}
} else {
header('HTTP/1.0 404 Not Found');
echo "File not found";
}请将此代码视为未经测试,并在将其发布到生产环境之前检查其在浏览器中是否按预期工作。
发布于 2016-01-19 18:04:15
这就是解决方案!
你可以使用.htacess文件来控制头部,这是一种更简单的头部管理方式。
你能做什么?
让我们举个例子,我有一个叫做"testPDF.pdf“的
文件,它位于我的站点的根文件夹中。你所要做的就是将下面的代码粘贴到.htaccss文件中。
<Files testPDF.pdf > Header add Link '<http://<your_site_name>.com/ >; rel="canonical"' </Files>
一旦将其添加到.htaccess文件中,就需要测试您的头文件以确保它能够正确工作
发布于 2019-02-12 13:28:40
对于IIS解决方案,请尝试如下所示。
Response.AppendHeader("Link", "<" + "https://" + Request.Url.Host + "/" + product.GetSeName() + ">; rel=\"canonical\"");这被添加到一个生成PDF版本的网页的函数中:)
https://stackoverflow.com/questions/14637238
复制相似问题