nginx使用重写为dynamic404图像

我想获得一个dynamic的404响应取决于请求的url:

foo.jpg不存在

http://example.com/img/style/thumbnail/foo.jpg 

应该显示

 http://example.com/img/notfound/thumbnail.jpg 

具有404头状态

我得到了正确的重写部分,但我似乎无法得到它与404状态代码返回。
我用下面的代码尝试了这个,但没有成功:

 location ~ /img { if (!-f $request_filename){ rewrite "^(.*img\/)style\/([a-zA-Z\_\-[0-9]*)\/?(.+)" $1notfound/$2.jpg; #so far so good. Now i want to return the rewrite result as a 404 response error_page 404 = $request_filename; return 404; } } 

这给了我默认的nginx 404错误页面,而不是重写的URL与404状态码。 我如何告诉nginx使用404错误页面的重写结果?

你误解了$request_filenamevariables。 它表示映射到文件的物理path ,考虑根和别名伪指令值以及正在处理的当前URI。

所以你的error_page指令将在内部redirect到一个对应于不存在的物理path的URI,因为它与被testing的path相同,进入你的if块。

Operator = in error指令不是问题,它只是告诉nginx保持当前的错误代码。 你也正在逃避你不需要的正则expression式中的一些符号,它会伤害到可读性。

所以,你的if块确实做了什么位置块做正则expression式。

你可以简单地把它减less到:

 location /img { location ~ ^/img/style/([_-a-zA-Z0-9]*) { error_page 404 /img/notfound/$1.jpg; } } 

我认为error_page 404 = $request_filename;

应该

error_page 404 $request_filename;

根据ngx_http_core_module文档

如果你的文件不存在,它应该返回默认的404而不是200。

只要告诉nginx返回这个文件的所有404错误。

这个代码应该放在你的条件之上,并放在你的位置块中:

 location ~ /img { error_page 404 /srv/www/static/img/notfound.jpg; if (!-f $request_filename){