How to url-rewrite image request?

0 votes
asked Oct 4, 2016 by jacekn

I'm making use of url rewriting. Lots of good information here and I have a working solution but I would like to do a bit better.

My Limited Solution

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RedirectMatch (.*)\.(gif|jpg|png)$ http://www.somesite.com$1.$2
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

The above redirects image requests fine but I'm building multiple sites in multiple languages and I would like to improve in the following way:

/attachments/1/canada-flag-small.1.jpg -> http://www.somesite.com/attachments/1/1.jpg
/jointes/2/usa-petit.1001.png -> http://www.somesite.com/attachments/2/1001.png

Basically, all extensions within parentheses (gif|jpg|png) should redirect to http://www.somesite.com/attachments. So the first token in image source needs to be completely ignored.

The second token in image source is important, as it's the directory storing the image and it should be included in the rewritten url.

The name of the image in image source should be ignored but the id of the image which follows the name and the extension need to form the image name we redirect to.

If it makes it any easier, there will be no slashes in the image name.

My own attempts result in Internal Server Error. Hopefully, someone here is willing to take a look at this. I've seen similar examples, where folks start with image id, add a dash and then add a descriptive image name. I would prefer to use style shown above, as I will have images such as '3-wheel-atv.333.jpg' and I don't want any confusion where the image id is.

Desired Solution provided by Croises

RewriteRule ^[^/]+/([^/]+)/(?:.*?\.)?(\d+\.(gif|jpg|png))$ http://www.somesite.com/attachments/$1/$2 [NC,L]

This allows for images to be stored as attachments/folder1/1.jpg but used on pages with source such as /great-images/folder1/awesome-image.1.jpg.

1 Answer

0 votes
answered Oct 4, 2016 by croises

Try with:

RewriteEngine on

RewriteRule ^[^/]+/([^/]+)/(?:.*?\.)?(\d+\.(gif|jpg|png))$ http://www.somesite.com/attachments/$1/$2 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

If your second token, directory storing the image, is only a number, you can use:

RewriteRule ^[^/]+/(\d+)/(?:.*?\.)?(\d+\.(gif|jpg|png))$ http://www.somesite.com/attachments/$1/$2 [NC,L]
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...