starlings
starlings

Reputation: 461

Rewrite image url with htaccess

This htaccess example is marked as running. I have no experience with htaccess. What I want to do is rewrite the image urls with htaccess.

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} -f 
RewriteCond %{REQUEST_URI} (?i)(jpg|jpeg|png|gif)$ 
RewriteCond %{QUERY_STRING} h=([1-9]) [OR] 
RewriteCond %{QUERY_STRING} w=([1-9]) 
RewriteRule (.*) resize.php?src=%{REQUEST_URI}&%{QUERY_STRING}

My htaccess and resize.php in same directory. and my image:

<img src="<?= make_image($row->imgage,750,422); ?>">

image helper

function make_image($url, $w, $h){ 
  $str = parse_url($url);
  $exp = explode("/", $str["path"]);  
  $file = end($exp);
  $new_url = str_replace($url, 'https://www.example.com/public/tt/img/', $url);
  return $new_url . $file . '?h='.$h.'&w='.$w; 
}

Directories:

enter image description here

And the result: enter image description here I would appriciate any suggestions, thank you.

Upvotes: 1

Views: 1128

Answers (2)

starlings
starlings

Reputation: 461

I solved the problem. I had to define two different patterns.

RewriteEngine on
RewriteCond $1 !^(resize\.php)
RewriteRule ^(img)/(.*)-([0-9]{1,4})x([0-9]{1,4}).(jpg) resize.php?src=https://www.example.com/public/image/$2.$5&w=$3&h=$4 [L]
RewriteRule ^(uploads/(?:[0-9]{4}|members))/(.*)-([0-9]{1,4})x([0-9]{1,4}).(jpg) resize.php?src=https://www.example.com/public/$1/$2.$5&w=$3&h=$4 [L]

Upvotes: 1

MrWhite
MrWhite

Reputation: 45968

RewriteCond %{REQUEST_FILENAME} -f 

This condition checks that the requested image URL maps to a physical file. However, according to your filesystem diagram, any request of the form /public/tt/img/<filename> does not exist as a physical file (there is no /public/tt/img directory), so the rule is never going to be processed.

It looks like you need to negate this condition and check that the request does not already map to a physical file, instead of checking that it does?

To do this, you need to prefix the CondPattern with a !. For example:

RewriteCond %{REQUEST_FILENAME} !-f 

Upvotes: 1

Related Questions