我开始编写自己的映像主机,但我遇到了一个小问题:
如果你通过浏览器直接查看链接(例如Domain.com/img/123),我想显示一个HTML页面,如果你通过嵌入链接,我想展示一个图像
<img src="Domain.com/img/123">
以便于使用。
是否可以检测链接是直接查看的,还是使用PHP嵌入的?
您可以为此使用htaccess
文件:
当浏览器加载嵌入图像时,他已经知道预期的格式,因此在请求文件时,他会将这些信息添加到HTTP:Accept
标头中。(或者至少将其简化为任何图像类型)
如果浏览器直接访问文件(地址栏中的url),他不知道这一点,所以他会将text/html
添加到HTTP:Accept
标头中。
铬提取物:
直接:Accept text/html, application/xhtml+xml, */*
嵌入式:Accept image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5
使用这些信息来捕捉直接访问的情况:下面的示例将把http://localhost/test/myimage.gif
上的access重定向到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的行为应该如您所期望的那样:
- 如果请求Uri以斜杠结尾,后面只有数字(即
/2537263
),则认为它符合重写条件 - 如果是diret访问(Http Accept表示text/html/em>),则会重写为
wrapperpage.php
- 如果是嵌入式访问(HTTP Accept表示而不是*text.html),则会将其重写为
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图像