Redirect non existing images that begins with letter a to no-photo-A.jpg

Viewed 31

I'm trying to redirect all non existing images to np-photo.jpg but I need some diversification:

  • If requestet file begins with letter "A" it should be redirected to no-photo-A.jpg
  • If requestet file begins with letter "B" it should be redirected to no-photo-B.jpg
  • ...

I have code:

Options +FollowSymLinks
RewriteEngine ON
RewriteCond %{REQUEST_URI} "/images/"
RewriteCond %{REQUEST_FILENAME} ^a.*\.jpg(jpeg|jpg|gif|png)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+) /images/no-photo-A.jpg [L,R=301] 

problem is with:

RewriteCond %{REQUEST_FILENAME} ^a.*\.(jpeg|jpg|gif|png)$

If I remove letter a then it matches all requests but I cannot force it to match only filenames that begins with specyfic letter.

https://domainname.pl/images/a11.jpg -should be redirected
https://domainname.pl/images/b11.jpg -should not be redirected
2 Answers

You may use a single rule like this:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/([A-Z0-9])[\w-]*\.(?:jpe?g|gif|png)$ /images/no-photo-$1.jpg [L,R=301,NC,NE]

This will redirect an non-existing /images/A-foo-bar.jpg to /images/no-photo-A.jpg.

With your shown samples, please try following htaccess Rules. Make sure your htaccess file is present along with images folder(NOT inside it).

Make sure to clear your browser cache before testing your URLs.

Options +FollowSymLinks -MultiViews
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1/no-photo-$2.jpg [NC]
RewriteRule ^(images)/(?:A|B)(.*)\.(?:jpeg|jpg|gif|png)$/?$ $1/no-photo-$2.jpg [R=301,NC,L]
Related