4

I'm REALLY bad with .htaccess files, and reading through the existing questions on SO only confuse me more (mainly because they're all situation-specific and don't exactly apply to my situation at hand). I'm making a script that generates dynamic images through PHP. The script takes 1 variable, which makes the URL look like this:

http://www.example.com/script/image.php?name=esqew

However, I'd like to utilize an .htaccess file to rewrite the file to something more elegant and something my users can use on forums, like so:

http://www.example.com/script/esqew.png

The question, in a nutshell, is how do I rewrite the first request above to something more elegant like the second example using .htaccess?

2 Answers 2

5

Please the following in your .htaccess file:

RewriteEngine On
RewriteRule ^script/(\w+)\.png$ script/image.php?name=$1 [L]

This assumes name is at least 1 alphanumeric or underscore character. It will also only work for png extensions.

1
  • Should I put this in my .htaccess within the directory, or at the root of my site?
    – esqew
    Commented May 15, 2011 at 20:44
3

Use this code in .htaccess file:

Options +FollowSymlinks -MultiViews
RewriteEngine on

RewriteRule ^(script)/([^.]*)\.png$ $1/image.php?name=$2 [L,NC]
4
  • Thanks for the answer, but the other guy beat you by just a few seconds. :)
    – esqew
    Commented May 15, 2011 at 19:36
  • Agreed and quite similar answers too, except that I am using [^.] instead of \w :)
    – anubhava
    Commented May 15, 2011 at 19:39
  • IMO, [^.] is too open in such a case assuming the OP is matching a filename.
    – Jason McCreary
    Commented May 15, 2011 at 19:42
  • Nope, because a valid filename can very well be esqew-1 and in that case \w+ will NOT match.
    – anubhava
    Commented May 15, 2011 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.