【问题标题】:Rewrite PHP Query URL to Image with .htaccess Mod Rewrite Rule使用 .htaccess Mod 重写规则将 PHP 查询 URL 重写为图像
【发布时间】: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

时显示虚拟 PHP 文件的内容

我尝试了[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


【解决方案1】:

这应该可以。浏览器可能需要重启。

RewriteEngine on
RewriteCond %{QUERY_STRING} ^image=(.*)$
RewriteRule ^.*img\.php$ ./img/%1 [NC,QSA]

相关:mod rewrite Rule for Image + String to Imagefolder Rewrite

【讨论】:

    【解决方案2】:

    您没有重定向。添加重定向标志,最后尝试[R]

    RewriteRule ^.+img\.php\?.*?image\=(.+)[$&] ./img/$1 [R,NC]
                                                          ^ 
    

    【讨论】:

    • 谢谢,但是当我访问 url 时,它显示“找不到对象”。抱歉,我可能误用了“重定向”这个词。我只想显示位于带有查询 url 的 img 目录中的图像。我不确定根据我的需要来描述它的正确短语是什么。
    • 对,那不是 HTTP 重定向,但您正在重写 URL。添加 R 可能会对您有所帮助,因为它使重写可见。无论如何,在您的情况下,只需启用重写日志并将日志中的相关部分添加到您的问题中。
    • Adding the R might help you, - 如果你的意思是[R,NC],它似乎不起作用。 just enable the rewrite logging and add the relevant part from the log to your question - 嗯,我不知道该怎么办。我试试,谢谢。
    • httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritelog - 日志记录了重写发生的情况。这样您就可以看到发生了什么(以及出了什么问题)。
    • 感谢您提供有关日志记录的信息。我在httpd.conf 中添加了RewriteLog "Z:\xampp\htdocs\rewrite.log" 并重新启动了Apache。它创建了一个名为 rewrite.log 的文件,但尽管访问了查询 url,但没有记录任何内容。文件大小保持在 0 kb。
    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多