Tony
Tony

Reputation: 333

Using htaccess to rewrite URL using an ID to a JPG filename

I currently have URLs like this:

/video/245008/245008_00000001.jpg
/video/245008/245008_00000002.jpg
etc.

I need htaccess to rewrite the above urls to be:

/video/245008/245008_1.jpg
/video/245008/245008_2.jpg

But only if the original 00000001.jpg, etc do not exist. Any suggestions?

Upvotes: 1

Views: 49

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

Try adding these rules to the htaccess file in your document root (the one that has the video directory):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/video/([0-9]+)/\1_0+([1-9][0-9]*)\.jpg$
RewriteCond %{DOCUMENT_ROOT}/video/%1/%1_%2.jpg -f
RewriteRule ^ /video/%1/%1_%2.jpg [L]

The first condition checks that the current request points to a file that doesn't exist. The second condition checks that the request is for something in the video directory, 2 gorups of identical numbers, and underscore with at least one zero following it, then some more numbers. The third condition checks that the new URI points to a file that does exist.

Upvotes: 1

Related Questions