Jesse Elser Jesse Elser - 1 month ago 7
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:

http://example.com/watermark.php?filename=assets/img/temp/temp_share.jpg
would result in
temp_share.jpg
having a watermark on the new image.

I'm trying to use
mod_rewrite
to clean up the URL to something like
http://example.com/filename/assets/img/temp/temp_share.jpg


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
http://example.com/filename/assets/img/temp/temp_share.jpg
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/m.style.css assets/styles/m.style.php [L]

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

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

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin http://lucycypher.com
Header set Access-Control-Allow-Credentials true
</IfModule>


Contents of
watermark.php
:

$imgpath=$_REQUEST['filename'];
header('content-type: image/jpeg');
$watermarkfile="assets/img/logo_variations/logo_watermark_75.png";
$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);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);

Answer

[^/] 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.

Comments