[英]Mod_Rewrite: htaccess rule to rewrite image URL
How can we use Apache Mod_Rewrite inside .htaccess file to rewrite real paths of.png files only?我们如何在 .htaccess 文件中使用 Apache Mod_Rewrite 仅重写.png 文件的真实路径?
Visible URL:可见URL:
.com/italy/region/internal/map1234.png
.com/italy/country/map1234.png
.com/italy/map1234.png
Real location of file:文件的真实位置:
.com/images/map1234.png
Note I refer to Mod_Rewrite and not a common 301 redirect.注意我指的是 Mod_Rewrite 而不是常见的 301 重定向。
RewriteCond %{REQUEST_URI}./images/.* RewriteRule ^(.*\,(gif|jpg|png))$ images/$1 [QSA,L]
it works but not for sub-folders.
它有效,但不适用于子文件夹。
This would have still redirected images in subfolders, but /italy/region/internal/map1234.png
would have been redirected to /images/italy/region/internal/map1234.png
.这仍然会重定向子文件夹中的图像,但
/italy/region/internal/map1234.png
将被重定向到/images/italy/region/internal/map1234.png
。
To make it work for any subfolders then change it to read:要使其适用于任何子文件夹,请将其更改为:
RewriteCond %{REQUEST_URI} !/images/
RewriteRule /(\w+\.(gif|jpg|png))$ images/$1 [L]
\w+
(previously .*
) - By excluding a slash in the captured pattern we ensure that we only capture the filename and not the entire URL-path. \w+
(以前是.*
) - 通过在捕获的模式中排除斜线,我们确保我们只捕获文件名而不是整个 URL 路径。
The QSA
flag is not required.不需要
QSA
标志。
UPDATE: Unfortunately this code fails (404) if I use images with dash.
更新:不幸的是,如果我使用带有破折号的图像,此代码将失败(404)。 For example my-name.png Any idea?
例如 my-name.png 有什么想法吗?
Change the \w
(any word character) in the above regex to [\w-]
to include a hyphen.将上述正则表达式中的
\w
(任何单词字符)更改为[\w-]
以包含连字符。 For example:例如:
RewriteRule /([\w-]+\.(gif|jpg|png))$ images/$1 [L]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.