Search code examples
apache.htaccessmod-rewrite

How to redirect urls for images with .htaccess?


Old urls:

1. https://example.com/images/1/image1.png
2. https://example.com/images/2/image2.png
3. https://example.com/images/3/image9.jpg
4. https://example.com/images/4/image19.jpg

New urls:

1. https://example.com/images/101.png
2. https://example.com/images/202.png
3. https://example.com/images/309.jpg
4. https://example.com/images/419.jpg

Rules:

  1. folder "1" + "0" + "1.png"
  2. folder "2" + "0" + "2.png"
  3. folder "3" + "0" + "9.jpg"
  4. folder "4" + "19.jpg"

Now I have this code for .htaccess:

RewriteEngine On

# Rewrite HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R=301,L]

# Rewrite index.php to /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php
RewriteRule ^index\.php$ / [R=301,L]

# Rewrite Query/ to Query
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+)/$ /$1 [R=301,L]
RewriteRule ^24$ / [R=301,L]

# Rewrite Query to index.php?route=Query
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?route=$1 [QSA,L]

Solution

  • Immediately after the RewriteEngine On line try the following:

    RewriteRule ^images/(\d+)/image(\d)\.(png|jpg)$ /images/$10$2.$3 [R=301,L]
    RewriteRule ^images/(\d+)/image(\d{2,})\.(png|jpg)$ /images/$1$2.$3 [R=301,L]
    

    The first rule handles the image names that contain a single digit (that must be prefixed with 0) and the second rule handles the rest.

    The $1, $2 and $3 backreferences match the corresponding capturing subgroups in the preceding RewriteRule pattern. In other words, $1 contains the folder name (all digits), $2 contains the number that appears after the filename and $3 contains the file extension (either jpg or png).

    NB: Test first with 302 (temporary) redirects to avoid potential caching issues.

    To clarify, presumably you are already linking to the new image URLs internally?