通过的.htaccess重定向图像请求取决于文件是否存在是否存在、重定向、图像、文件

2023-09-02 09:58:44 作者:先森们。你们滴良心在哪

我实现它保存在最终文件中的图像生成。 JPG 格式里面的 /图片。一旦文件被保存,没有必要产生它的以后再的。

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

这是该目录下所有的 JPG 图像保存:

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

/images/495abc.jpg

因此​​,其目标是:如果用户试图请求 http://website.com/images/495abc.jpg 。 htaccess的规则必须验证该文件是否存在,然后再执行的根据不同的情况下,以下两种情况之一:

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:

如果 JPG 的存在,直接服务于文件。

if the .jpg exists, serve the file directly.

如果 JPG 做的不可以存在,将请求重定向到发生器 /gen.php?id=495abc 的(新形象将在这个过程结束与标题(内容类型:image / JPEG))

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"))

是通过可行的的.htaccess ?如果没有,还有另外一种选择:重定向所有 /图像/ * JPG 要求 /gen.php?id = * 让 gen.php 做最脏最累的工作。当然,第一选择是更好。的

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.

任何想法?谢谢!

推荐答案

是的。这是可能的的htaccess

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