Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mod_rewrite – get images from subfolder for specific HTTP Host

I have very simply situation, but I still can’t make it works. My back-end controls more than one site and I need to make simple rewrite of /img/ folder to /img/subfolder/ for specific HTTP hosts.

So, from URL www.site1.com/img/logo.svg file will be in /img/logo.svg
and from URL www.site2.com/img/logo.svg will be in /img/site2/logo.svg

I have this code in .htaccess, but it throws 500 error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

RewriteCond %{HTTP_HOST} ^www.site2.com
RewriteRule ^img/(.*)$ img/site2/$1 [L]

What am I overlooking? Thank you!

>Solution :

RewriteCond %{HTTP_HOST} ^www.site2.com
RewriteRule ^img/(.*)$ img/site2/$1 [L]

This will throw a 500 error because the RewriteRule pattern also matches the target URL, which will result in an endless rewrite loop. You need to exclude requests that have already been rewritten to img/site2/, or perhaps just match img/<file>, instead of img/<anything>.

For example, try the following instead:

RewriteCond %{HTTP_HOST} ^www\.(site2)\.com
RewriteRule ^img/([^/]+\.\w{2,4})$ img/%1/$1 [L]

This matches /img/logo.svg, but not /img/site2/logo.svg.

The %1 backreference contains the domain name (ie. "site2") captured from the preceding CondPattern. This simple saves repetition.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading