【发布时间】:2012-10-07 13:15:20
【问题描述】:
如何将 PHP 查询 URL 重写为实际图像?
我希望将 http://localhost/img.php?image=winter.jpg 重写为 http://localhost/img/winter.jpg 图像名称动态变化。
我试过这样,但它不起作用。
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.+img\.php\?.*?image\=(.+)[$&] ./img/$1 [NC]
谢谢。
[更新]
在访问 http://localhost/img.php?image=winter.jpg 后,以下文本被附加到日志文件中。浏览器显示消息“找不到对象!在此服务器上找不到请求的 URL。如果您手动输入了 URL,请检查您的拼写并重试。”
127.0.0.1 - - [<time>] [localhost/sid#975148][rid#4d09cb8/initial] (3) [perdir Z:/xampp/htdocs/] strip per-dir prefix: Z:/xampp/htdocs/img.php -> img.php
127.0.0.1 - - [<time>] [localhost/sid#975148][rid#4d09cb8/initial] (3) [perdir Z:/xampp/htdocs/] applying pattern '^.+img\.php\?.*?image=(.+)[$&]' to uri 'img.php'
127.0.0.1 - - [<time>] [localhost/sid#975148][rid#4d09cb8/initial] (3) [perdir Z:/xampp/htdocs/] pass through Z:/xampp/htdocs/img.php
[更新]
错误日志说,
[<time>] [error] [client 127.0.0.1] script 'Z:/xampp/htdocs/img.php' not found or unable to stat
所以我创建了一个名为img.php 的虚拟文件,并且错误声明不再显示。我假设不需要一个虚拟文件。现在它只在我访问 http://localhost/img.php?image=winter.jpg
我尝试了[NC,L]、[R,NC]、[R,NC,L],但都没有奏效。
【问题讨论】:
-
所以在完成重写日志之后,现在你需要查看错误日志(通常默认情况下已经启用)。在该错误日志中,将解释 404 错误,例如一直在寻找哪个文件。同样从重写日志来看,您应该将该规则标记为
[L]。 -
@hakre 感谢您的跟进。我更新了问题。
-
您要阅读此内容:simonecarletti.com/blog/2009/01/… - URL 的查询字符串部分需要特殊处理,您不能在
RewriteRule中对其进行正则表达式。基本上 404 意味着您的 URL 没有被重写(您的正则表达式不匹配)。 -
我明白了。我尝试了
RewriteCond %{QUERY_STRING} ^image=(.*)$ RewriteRule ^img\.php$ ./img/%1 [NC,L],现在浏览器将 url 重写为http://localhost/Z:/xampp/htdocs/img/winter.jpg?image=winter.jpg似乎文件路径和 url 混合在一起。该页面显示 403 错误,并显示一条消息“禁止访问!”。
标签: php apache .htaccess mod-rewrite redirect