我试图在我的网站数量的PDF和图像文件设置规范链接。
例如文件夹结构:
/index.php
/docs/
file.pdf
/folder1/
file.pdf
/folder2/
file1.pdf
file2.pdf
/img/
sprite.png
/slideshow/
slide1.jpg
slide2.jpg
例如PDF的URL规范网址:http://www.example.com/docs/folder1/file.pdf --> http://www.example.com/products/folder1/
我试图避免把个人.htaccess文件中的每一个包含所有我的图片和PDF文件的子文件夹。我公司目前拥有7“主”文件夹,每个文件夹中都有2-10子文件夹的任何地方,大多数子文件夹都有自己的子文件夹。我有大约80 PDF文件,甚至更多的图像。
我正在寻找一个(半)的动态解决方案,其中在特定的文件夹中的所有文件都会有规范链接设置为一个URL。我想保持尽可能在一个.htaccess文件。
我知道<Files>
和<FilesMatch>
不懂路径,并且<Directory>
和<DirectoryMatch>
不要在.htaccess文件。
是否有一个相当简单的方式来做到这一点?
我不知道的方式单独apache的规则来解决这个问题,因为这将需要某种形式的正则表达式匹配和再利用比赛的指令,这是不可能的结果。
但是,如果你介绍一个PHP脚本到混合这是很简单的:
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|png|pdf)$
RewriteRule (.*) /canonical-header.php?path=$1
请注意,这将发送所有JPG,PNG和PDF文件的请求,该脚本不管文件夹名称。如果你想只包括特定的文件夹,你可以添加其他的RewriteCond来实现这一目标。
现在规范-的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";
}
请考虑下面的代码未经测试,并确认其工作跨浏览器按预期释放到生产前。
这里是解决方案!
您可以使用.htaccess文件控制头,其管理标题更简单的方法。
你能怎么办?
让我们一个例子,我有一个名为“testPDF.pdf” PDF这是在我的网站的根文件夹。所有你需要做的,粘贴以下代码.htaccss文件。
<Files testPDF.pdf >
Header add Link '<http://<your_site_name>.com/ >; rel="canonical"'
</Files>
一旦你还说,你的.htaccess文件,你需要测试你的头,以确保它的工作准确
对于IIS的解决方案,尝试这样的事情。
Response.AppendHeader("Link", "<" + "https://" + Request.Url.Host + "/" + product.GetSeName() + ">; rel=\"canonical\"");
这是加入到生成的网页的PDF版本的功能:)