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:


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:


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


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.

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

Use this code in .htaccess file:

Options +FollowSymlinks -MultiViews
RewriteEngine on

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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