【问题标题】:htaccess get file and extension without pathhtaccess 获取没有路径的文件和扩展名
【发布时间】:2016-03-26 22:21:56
【问题描述】:

我已经尝试了很长时间,但仍然无法解决。我试过htaccess get filename without path,但它对我不起作用。

这是我的目录

/www
|-- /other.org
|-- /example.com
    |-- /sub 
        |-- .htaccess
        |-- success.html
        |-- /imgs
            |-- photo.png

当http://example.com/sub 有对该图像或文件的请求时,我正在尝试查找该图像是否存在于http://example.com/sub/imgs。如果存在,则用户将被重定向到 success.html。但我不能那样做。

例如,如果我在浏览器中输入

http://example.com/sub/photo.png

它检查文件 photo.png 或任何类型的图像是否存在于 /sub/imgs/photo.png 中,它不存在并且不应该存在于 /sub 目录中。

http://example.com/sub/imgs/photo.png

如果存在,重定向的输出将是success.html。

http://example.com/sub/success.html

我试过了

RewriteCond %{DOCUMENT_ROOT}/sub%{REQUEST_URI} -f
RewriteRule (.*)\.(gif|jpg|jpeg|png)$ success.html

但%{REQUEST_URI} 是/sub/photo.png,所以输出将是http://example.com/sub/imgs/sub/photo.png。没有任何请求可以获取文件名或最后一个斜杠 (/) 之后的任何内容。是否可以只获取文件名photo.png 所以我可以这样做:

RewriteCond %{DOCUMENT_ROOT}/sub/imgs%{FILE_NAME} -f
RewriteRule (.*)\.(gif|jpg|jpeg|png)$ success.html

有什么办法可以让它工作吗?

【问题讨论】:

  • RewriteCond %{DOCUMENT_ROOT}/sub/imgs/$1 -f RewriteRule ^.+/(.+\.jpeg?|png|gif)$ /redirect.html [L]
  • @starkeen 嗨,它对我不起作用,我编辑了问题以修复一些目录错误。我想我刚才进入目录的方式是错误的。

标签: apache .htaccess redirect mod-rewrite


【解决方案1】:

你可以在sub/.htaccess试试这个规则:

RewriteEngine On
RewriteBase /sub/

RewriteCond %{DOCUMENT_ROOT}/sub/imgs/$1 -f
RewriteRule ^(.+\.(?:jpe?g|png|gif|tiff|ico))$ success.html [L,NC]

【讨论】:

  • 嗨,你能告诉我最后一行是做什么的吗? (.+\.(?:jpe?g|png|gif|tiff|ico))
  • 最后一行匹配以任何这些扩展名jpe?g|png|gif|tiff|ico 结尾的任何图像名称。 (?:..) 称为非捕获组
  • 谢谢!我读了stackoverflow.com/questions/3512471/…,但还是不明白这里是干什么用的?
  • 我们也可以在此规则中使用(jpe?g|png|gif|tiff|ico),但这称为捕获组,因为它将图像扩展名放在`$2.但是在这里我们不想捕获它,所以使用非捕获组。
  • 我可以知道如果我们在这里使用捕获组会发生什么以及它是如何完成的吗?我将 html 更改为 php 并读取图像,但图像不显示,而是显示 gremlins,不知道为什么会发生这种情况或如何修复它。我已经放了内容类型标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 2023-03-10
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多