简体   繁体   中英

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?

Visible 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.

 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 .

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.

The QSA flag is not required.

UPDATE: Unfortunately this code fails (404) if I use images with dash. For example my-name.png Any idea?

Change the \w (any word character) in the above regex to [\w-] to include a hyphen. For example:

RewriteRule /([\w-]+\.(gif|jpg|png))$ images/$1 [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM