【发布时间】:2015-04-02 13:14:57
【问题描述】:
我开始写自己的镜像宿主但是我有一个小问题:
如果您通过浏览器直接查看链接(例如 Domain.com/img/123),我想显示一个 HTML 页面,如果您通过
嵌入链接,我想显示一个图像<img src="Domain.com/img/123">
方便使用。
是否可以检测链接是直接查看的还是用PHP嵌入链接的?
【问题讨论】:
我开始写自己的镜像宿主但是我有一个小问题:
如果您通过浏览器直接查看链接(例如 Domain.com/img/123),我想显示一个 HTML 页面,如果您通过
嵌入链接,我想显示一个图像<img src="Domain.com/img/123">
方便使用。
是否可以检测链接是直接查看的还是用PHP嵌入链接的?
【问题讨论】:
您可以为此目的使用htaccess 文件:
当浏览器加载一个嵌入的图像时,他已经知道期望的格式,所以他会在请求文件时将此信息添加到HTTP:Accept 标头中。 (或至少将其减少为任何图像类型)
如果浏览器直接访问文件(地址栏中的 url),他不知道这一点,所以他会将text/html 添加到HTTP:Accept Header。
从 chrome 中提取:
直接:Accept text/html, application/xhtml+xml, */*
嵌入式:Accept image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5
使用此信息来捕获直接访问案例:下面的示例将在 http://localhost/test/myimage.gif 上的访问重定向到 index.php?url=/test/myimage.gif。
RewriteEngine on
RewriteCond %{REQUEST_URI} .*\.gif # redirect gifs
RewriteCond %{REQUEST_URI} !.*index\.php # make sure there is no loop
RewriteCond %{HTTP:Accept} .*text/html.* # redirect direct access
RewriteRule (.*) http://localhost/test/index.php?url=$1 [R,L]
像http://localhost/test/test.php 这样的另一个文件可以正确使用<img src="http://localhost/test/myimage.gif" /> 不会发生重定向,因为不会发送Accept: text/html。
请记住,这对测试有点不利:一旦您将图像嵌入某处,当您直接访问该图像时,浏览器缓存将不再加载数据。因此看起来直接访问是可能的。但是,如果您按 F5 刷新缓存的图像,则会应用重定向。 (让调试工具保持打开状态以禁用缓存)
关于您的评论。我忽略了您想随时使用人工 url 来呈现图像。这改变了设计 htaccess ofc 的方式。
以下 htaccess 的行为应该与您预期的一样:
/2537263),则认为它符合重写条件。wrapperpage.php
image.php
htaccess:
RewriteEngine on
RewriteCond %{REQUEST_URI} /\d+$
RewriteCond %{HTTP:Accept} .*text/html.*
RewriteRule ^(.*?)$ http://localhost/test/wrapperpage.php?id=$1 [R,L]
RewriteCond %{REQUEST_URI} /\d+$
RewriteCond %{HTTP:Accept} !.*text/html.*
RewriteRule ^(.*?)$ http://localhost/test/image.php?id=$1 [R,L]
注意:如果您省略 [R] 选项,用户将不会看到 URL 中反映的重定向。
我使用的示例页面代码:
wrapperpage.php:
THIS IS MY WRAPPER PAGE:
<br />
<img src = "http://localhost/test/<?=$_GET["id"]?>" />
<br />
IMAGE IS WRAPPED.
image.php(我假设你确定图片的逻辑在那里)
<?php
//Load Image
$id = $_GET["id"];
//pseudoloading based on id...
// loading...
// done.
$image = imagecreatefromgif("apache_pb.gif");
//output image as png.
header("Content-type: image/png");
imagepng($image);
?>
所以:
http://localhost/test/1234 在浏览器中 -> wrapperpage.php?id=1234
http://localhost/test/1234 嵌入 -> image.php?id=1234
http://localhost/test/image.php?id=1234 -> 返回 png 图像。【讨论】:
RewriteCond %{REQUEST_FILENAME} !-f 你的意思是:只应用规则,如果该文件不存在 - 这对于你想要的目的没有意义使用它。