Magento – Rewrite rule for media images

.htaccess301-redirectmagento2nginxredirect

we need to set rewrite rule for some images in Magento 2.2.5 using .htaccess rules or nginx conf


Example 1

Request Path:

https://www.example.com//media/catalog/product/cache/1/thumbnail/543×403/db978388cfd007780066eaab38556cef/n/u/number1.png

Response Path:

https://www.example.com/pub/media/catalog/product/cache/543×403/n/u/number1.png


Example 2

Request Path :

https://www.example.com/media/catalog/product/cache/1/thumbnail/543×403/db978388cfd007780066eaab38556cef/l/e/legal_slide01.jpg

Response Path :

https://www.example.com/pub/media/catalog/product/cache/543×403/l/e/legal_slide01.jpg


Here the l/e/ directories are set according to the first two characters of image name here: legal_slide01.jpg

Thank you

Best Answer

You can use the following RewriteRule in the .htaccess file inside the media folder. Just add this two lines right below RewriteEngine on:

RewriteCond %{REQUEST_URI} ^/media/catalog/product/cache/1/thumbnail/(.*)/db978388cfd007780066eaab38556cef/(.*)$
RewriteRule "^.*/thumbnail/(.*)/db978388cfd007780066eaab38556cef/(.*)$" /pub/media/catalog/product/cache/$1/$2 [R=301,NC,L]

This rule will do a 301 redirect, if you just want to serve the imagase with the original URL and do an internal redirect, just remove R=301 from the rule's options.

I hope that helps

Related Topic