Question

I am trying to do clean URLs for images, where the url also contains a description of the image (for seo purposes). The only important part of the file name is the start and the extension.

I am trying to get like image URLs such as:

mywebsite.com/seo-images/123-some-description.jpg

to do a clean url rewrite where the image is actually located at

mywebsite.com/uploads/123.jpg

file types can be .jpg or .png or .gif etc.

I also have thumbnails:

mywebsite.com/seo-images/t123-some-description.jpg

to do also do a clean url rewrite in the same way and place

mywebsite.com/uploads/t123.jpg

I have tried putting the following .htaccess file in the seo-images directory

RewriteEngine On
RewriteBase /seo-images/

# match all numbers upto - then get the extension after .
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([_0-9a-zA-Z-]+/)?-([_0-9a-zA-Z-]+/)?([_0-9a-zA-Z-]+/)\.$ /uploads/$1.$3 [R=301,L]

so far, no good.

I have a .htaccess file in the root that does other clean mod_rewrites.

The "some-description" can be one word or many words separated by - so basically everything after the - and before the . should be disregarded and the new filename used to rewrite using the new filename in a different directory

Was it helpful?

Solution

I think you would use rather this simpler rules set in /seo-images/.htaccess, we rewrite only if %{REQUEST_FILENAME} is neither a file nor a directory, not the inverse:

RewriteEngine On
#RewriteBase /seo-images/

# match all numbers upto - then get the extension after .
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]+)-.*\.([[:alnum:]]+)$ /uploads/$1.$2 [L]

Without redirect, we use only an internal rewrite, Google will always think about mywebsite.com/seo-images/123-some-description.jpg instead of mywebsite.com/uploads/123.jpg .

Or you prefer absolutely rewriting:

RewriteEngine On
#RewriteBase /seo-images/

# match all numbers upto - then get the extension after .
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]+)-.*\.([[:alnum:]]+)$ /uploads/$1.$2 [R=301,L]

It does this:

/seo-images/123-some-description.jpg => /uploads/123.jpg
/seo-images/t123-foo-bar.png => /uploads/t123.png
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top