Webmasters Stack Exchange is a question and answer site for pro webmasters. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In a webshop I've build I want to make the imagename more seofriendly.
It's now a uniqid(), in my example the filename will be 1243:

I've got the following working, I want the htaccess to check the following:
if 1234.jpg exists -> redirect to the jpg
if 1234.jpeg exists -> redirect to the jpeg
if 1234.png exists -> redirect to the png
(not in the code, but a all 3 dont exist-> redirect to no-image.jpg would be great)

I have the following code (this is a simplefied version!), but I feel this could be done more efficient:

RewriteCond %{REQUEST_URI} ^/product_images/([0-9]+)
RewriteCond %{DOCUMENT_ROOT}/images/%1.jpeg -f
RewriteRule ^product_images/([0-9]+) images/$1.jpeg [L]

RewriteCond %{REQUEST_URI} ^/product_images/([0-9]+)
RewriteCond %{DOCUMENT_ROOT}/images/%1.jpg -f
RewriteRule ^product_images/([0-9]+) images/$1.jpg [L]

RewriteCond %{REQUEST_URI} ^/product_images/([0-9]+)
RewriteCond %{DOCUMENT_ROOT}/images/%1.png -f
RewriteRule ^product_images/([0-9]+) images/$1.png [L]
  • All 1st lines are identical and will remain that way
  • All 2nd lines are the same, apart from the .ext
  • All 3rd lines are the same, apart from the .ext
  • Every 3rd line has the same .ext as the 2nd line

My .htaccess isn't bad, but I have no clue where to start with this. Anyone who can push me in the right direction? I prefer explanation above the plain answer, so I can fix this myself in the future

share|improve this question
up vote 1 down vote accepted

As you say, in all three rule sets the first rule is the same. So you might benefit from nested conditions...

Here's an existing answer that should get you started.


Also you may find it useful when optimizing your rewrites to turn on your rewrite log.


I think there's a danger of over-optimizing here though. You're not likely to get a lot of real world performance improvement out of this. I think code readability and maintainability would be the priority for something like this.

share|improve this answer
Yeah, I can work with this :) thanks – Martijn Apr 24 '14 at 18:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.