tags:

views:

32

answers:

1

I have a table in my database which has information about a bunch of user uploaded images. One of the fields is "slug". Say the user uploads an image with the filename "46156142.jpg" and inputs the slug as "smiley-face", I want to be able to point to the image by navigating to "http://domain.com/smiley-face". The actual location of the file would be "http://domain.com/images/46156142.jpg".

Is this at all possible? I'm basically trying to replicate the effect of slugs in Wordpress, except for an actual image file.

+2  A: 

Yes this is possible but is not recommended. You need to use a .htaccess file to route all data sent to urls which are image slugs to a page that reads the database, looks up the filename for the corresponding slug and then redirects to that image.

A better way would be to rename the file when the user uploads the file to the slug. When the user goes to the slug, you can then use .htaccess to capture the slug and use the slug as the filename as no database lookup is required.

Once you have renamed the file such that it is located at http://domain.com/images/slug.jpg, you need to include the following in your .htaccess:

RewriteRule ^(.*)$ /images/$1.jpg [L]

However, the problem you will have is that there will likely be many urls of the form http://domain.com/anything/ which you do not want to map to an image. Therefore, it would be better to do the following:

RewriteRule ^image/(.*)$ /images/$1.jpg [L]

This will force uses to go to http://domain.com/image/slug instead of http://domain.com/slug but will avoid the above problem. Alternatively, you will have to create specific rules for any conflict you wish to avoid.

Rupert
I think I was starting to think along the same lines. Rename file so it's full url becomes "http://domain.com/images/slug.jpg" and then use regex to remove the "images/" and the ".jpg" parts so it becomes "http://domain.com/slug"... right?
Danny
Yup pretty much. I've edited my answer with more details on how to do this.
Rupert
Thank you, that's a great help. The entire point of what im building is the very short urls so I guess I will have to create specific rules for everything else.Thanks again!
Danny