I need to control all remotes .jpg matching sizes: 4456 and 4824. If match these bytes I need to replace with a default image. The below code is to replace a .jpg
if doesn't exist.
RewriteCond %{REQUEST_URI} \.(jpeg|JPEG|jpg|JPG)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*$ /default-image.jpg [L]
I need that if a example.com/*.jpg
have size (4456 | 4824) then replace with the default-image.jpg
.
In PHP this is working like a charm for my needs but I would prefer to set in .htaccess
.
$link = 'https://example.com/test.jpg';
$check_image = get_headers($link, 1);
$bytes = $check_image["Content-Length"];
if ($bytes < 5000) { ...
You can do the following on Apache 2.4 using an Apache expression with mod_rewrite:
RewriteCond %{REQUEST_URI} !^/default-image\.jpg$
RewriteCond expr "filesize(%{REQUEST_FILENAME}) =~ /4456|4824/"
RewriteRule \.jpe?g$ /default-image.jpg [NC,L]
If the requested image does not exist then the filesize()
function simply returns 0
(no error). So, to handle non-existent images as well, then you could just change the regex to include 0
, ie. /0|4456|4824/
.
Aside:
RewriteCond %{REQUEST_URI} \.(jpeg|JPEG|jpg|JPG)$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .*$ /default-image.jpg [L]
In the first condition, there is no need to check jpeg|JPEG
since you are using the NC
(case-insensitive) flag on the directive. However, it is more optimal to perform this check in the RewriteRule
pattern instead, rather than creating an additional condition.
There's no need to check that the request does not map to a directory (3rd condition), unless you also have directory names that end in .jpg
etc. (unlikely). Filesystem checks are relatively expensive, so it is best to avoid them if possible.