Jesse Elser Jesse Elser - 1 year ago 69
Apache Configuration Question

Using Mod_Rewrite With Image URL Parameters

I'm using a script to watermark images on the fly through a URL.

For example:
would result in
having a watermark on the new image.

I'm trying to use
to clean up the URL to something like

I used the generator at this site and it gave me
RewriteRule ^filename/([^/]*)$ /watermark.php?filename=$1 [L]

But when I try to go to
I get an error of
Not Found The requested URL /filename/assets/img/temp/temp_share.jpg was not found on this server.

I'm not sure what I've done wrong.

Full contents of my .htaccess

ErrorDocument 400 /err.php?err=400
ErrorDocument 401 /err.php?err=401
ErrorDocument 403 /err.php?err=403
ErrorDocument 404 /err.php?err=404
ErrorDocument 500 /err.php?err=500
ErrorDocument 502 /err.php?err=502
ErrorDocument 504 /err.php?err=504

Options -MultiViews
RewriteEngine On
RewriteBase /

RewriteRule assets/styles/style.css assets/styles/style.php [L]
RewriteRule assets/styles/ assets/styles/ [L]

RewriteRule ^filename/([^/]*)$ /watermark.php?filename=$1 [L]

<FilesMatch ".(jpg|png|gif|jpeg)$">
ErrorDocument 404 error/stormtrooperBrokenImage.jpg

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin
Header set Access-Control-Allow-Credentials true

Contents of

header('content-type: image/jpeg');
$watermark = imagecreatefrompng($watermarkfile);
list($watermark_width,$watermark_height) = getimagesize($watermarkfile);
$image = imagecreatefromjpeg($imgpath);
$size = getimagesize($imgpath);
$dest_x = ($size[0] - $watermark_width)/2;
$dest_y = ($size[1] - $watermark_height)/2;
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);

Answer Source

[^/] is a character class of all characters except for /

Since your file names do contain / you need to capture all characters after the "filename/" token. Try changing it to this.

RewriteRule ^filename/(.*)$ /watermark.php?filename=$1 [L]

After tripple checking that your rewrite module is enabled and you have done a server restart, if it still doesn't work you should consider enabling verbose rewrite debugging to log files.

You should also consider adding an extra security check on the image path. It is very easy for somebody to manipulate the filename param with things like ../../../sensitive_uploads/1.jpg to navigate to somewhere outside of your image directory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download