缺少图像时,Apache会提供默认图像

时间:2012-07-27 00:19:55

标签: image apache mod-rewrite

我们为产品提供了几种不同尺寸的图像。我们希望在缺少产品图像时返回正确尺寸的默认图像。

每种产品的图像路径都不同。     path /www/docroot/images/brand/product/product1_l.jpg     path /www/docroot/images/differentbrand/differentproduct/someotherproduct1_l.jpg 图像的大小类似于左侧的项目。我们希望在右侧选择相应的默认图像。

product1_l.jpg large    noimage_l.jpg
product1_m.jpg medium   noimage_m.jpg
product1_s.jpg small    noimage_s.jpg

我见过一些使用mod_rewrite实现类似功能的人的例子。任何人都可以就如何使用它来适应我的情景提供任何指导吗?

2 个答案:

答案 0 :(得分:0)

您需要一个智能404处理程序。如果Apache抛出404(找不到文件)错误,智能处理程序应该尝试通过查看URL的模式来挽救事件,并找到要服务的已知资源。您还应该处理后退图像可能也不存在的可能性。

此页面可以向您展示如何检查文件是否存在,但逻辑将需要在最后一行。

http://www.phpriot.com/articles/search-engine-urls/5

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

或者你可以去.htaccess路线(我认为那更干净)

http://httpd.apache.org/docs/2.2/mod/core.html#errordocument

假设您可以使用.htaccess和PHP,这是一个解决方案:

将此行添加到.htaccess:

ErrorDocument 404 /error.php

然后将此代码添加到error.php,就像这样

<?php
 if(preg_match("/^/images/thumbnail/", $_SERVER['REQUEST_URI'])) {
   //do a 302 redirect
   header( 'Location: /images/defualtImage.jpg' ) ;
 } else {
   //You need to go somewhere to handle actual 404 errors
   header( 'Location: /static/404.html' ) ;
 }
?>

302 redirect directs在这里效果最好。

答案 1 :(得分:0)

感谢您的所有评论。我们最终采用了不同的解决方案。我们使用onerror js标记指向适当的noimg位置。这对我们的环境来说更清洁,更容易