Redirecting image requests via .htaccess depending on file existence

狂风中的少年 提交于 2019-12-24 03:16:43

问题


I implemented an image generator which saves the final file in .jpg format inside /images. Once the file is saved, there is no need to generate it ever again.

This is the route for the image generator:

/gen.php?id=495abc

This is the directory where all the .jpg images are saved:

/images/495abc.jpg

So, the objective is: If a user tries to request http://website.com/images/495abc.jpg, the .htaccess rules have to verify if the file exists and then execute one of two actions depending on the case:

  1. if the .jpg exists, serve the file directly.

  2. if the .jpg does not exist, redirect the request to the generator at /gen.php?id=495abc (the new image will be displayed at the end of this process with Header("Content-Type: image/jpeg"))

Is that feasible via .htaccess? If not, there is another alternative: Redirect all /images/*.jpg requests to /gen.php?id=* and let gen.php do all the dirty work. Of course, the first alternative is better.

Any ideas? Thanks!


回答1:


Yes. It is possible with htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/(\d+)\.(jpe?g|png|gif|ico|bmp)$ /gen.php?id=$1 [L,NC]


来源:https://stackoverflow.com/questions/26949541/redirecting-image-requests-via-htaccess-depending-on-file-existence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!