您可以使用htaccess
为此目的文件:
当浏览器加载嵌入图像时,他已经知道期望的格式,因此他会将这些信息添加到HTTP:Accept
请求文件时的标头。 (或者至少将其减少为任何图像类型)
如果浏览器直接访问文件(地址栏中的 url),他不知道这一点,所以他会添加text/html
to the HTTP:Accept
Header.
从铬中提取:
direct: Accept text/html, application/xhtml+xml, */*
嵌入:Accept image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5
使用此信息来捕获直接访问情况:下面的示例将重定向访问http://localhost/test/myimage.gif
to 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
将被寄出。
请记住,这有点不好test:一旦将图像嵌入到某处,当您直接访问该图像时,浏览器缓存将不再加载数据。因此它看起来像直接访问是可能的。但是,如果您按 F5 刷新缓存的图像,则重定向将适用。
(保持调试工具打开以禁用缓存)
Update
至于你的评论。我忽略了你想随时使用人工 url 来呈现图像。这改变了htaccess ofc的设计方式。
以下 htaccess 的行为应符合您的预期:
- 如果请求 Uri 以斜线结尾,后跟数字(即
/2537263
)它被认为有资格重写。
- 如果是直接访问(Http-Accept说文本/html) 被重写为
wrapperpage.php
- 如果是嵌入式访问(HTTP-Accept说not*text/html) 被重写为
image.php
访问:
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 中反映的重定向。
我使用的示例页面代码:
包装页.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);
?>
So:
-
http://localhost/test/1234
在浏览器中->wrapperpage.php?id=1234
-
http://localhost/test/1234
嵌入->image.php?id=1234
-
http://localhost/test/image.php?id=1234
-> 返回 png 图像。