如何更改 nginx 中代理服务器响应的状态代码? [英] How to change the status code of a proxied server response in nginx?
问题描述
我很难将 nginx 配置为充当公共 S3 端点的代理.我的用例需要更改 S3 响应的状态代码,同时保留响应负载.
I'm having a hard time configuring nginx to act as a proxy of a public S3 endpoint. My use case necessitates altering the status code of the S3 response, while preserving the response payload.
S3 返回的可能状态代码包括 200 和 403.对于我的用例,我需要将这些状态代码映射到 503.
The possible status codes returned by S3 include 200 and 403. For my use case, I need to map those status codes to 503.
我尝试了以下不起作用的方法:
I have tried the following which does not work:
location ~* ^/.* {
[...]
proxy_intercept_errors on;
error_page 200 =503 $upstream_http_location
}
Nginx 输出如下错误:
Nginx outputs the following error:
nginx: [emerg] 值200"必须在/etc/nginx/nginx.conf:xx 中的 300 到 599 之间
nginx: [emerg] value "200" must be between 300 and 599 in /etc/nginx/nginx.conf:xx
这是一个更完整的片段:
Here's a more complete snippet:
server {
listen 80;
location ~* ^/.* {
proxy_http_version 1.1;
proxy_method GET;
proxy_pass http://my-s3-bucket-endpoint;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Connection "";
proxy_set_header Host my-s3-bucket-endpoint;
proxy_set_header Authorization '';
proxy_hide_header x-amz-id-2;
proxy_hide_header x-amz-request-id;
proxy_hide_header Set-Cookie;
proxy_ignore_headers "Set-Cookie";
proxy_cache S3_CACHE;
proxy_cache_valid 200 403 503 1h;
proxy_cache_bypass $http_cache_purge;
add_header X-Cached $upstream_cache_status;
proxy_intercept_errors on;
error_page 200 =503 $upstream_http_location;
}
}
是否可以通过 nginx 实现我所需要的?
Is it possible to achieve what I need with nginx?
推荐答案
我找到了一个或多或少合适的解决方案.这有点骇人听闻,但确实有效.
I found a more or less suitable solution. It's a bit hackish but it works.
关键是将我的 S3 存储桶的索引文档设置为不存在的文件名.这会导致对 S3 存储桶端点的/请求导致 403.
The key was to set the index document of my S3 bucket to a non-existing filename. This causes requests to / on the S3 bucket endpoint to result in 403.
由于 nginx 代理将所有传入请求映射到 S3 存储桶端点上的/,因此结果始终是 403,nginx 代理可以拦截.从那里,error_page 指令告诉它通过请求 S3 存储桶端点中的特定文档(在本例中为 error.json)来响应,并使用 503 作为响应状态代码.
Since the nginx proxy maps all incoming requests to / on the S3 bucket endpoint, the result is always 403 which the nginx proxy can intercept. From there, the error_page directive tells it to respond by requesting a specific document (in this case error.json) in the S3 bucket endpoint and use 503 as the response status code.
location ~* ^/. {
proxy_intercept_errors on;
error_page 403 =503 /error.json;
}
此解决方案涉及将两个请求发送到 S3 存储桶端点(/、/error.json),但至少似乎使用上面更完整片段中的配置为这两个请求启用了缓存.
This solution involves two requests being sent to the S3 bucket endpoint (/, /error.json) but at least caching seems to be enabled for both requests using the configuration in the more complete snippet above.
这篇关于如何更改 nginx 中代理服务器响应的状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!