如何在proxy_pass中设置内容类型?

时间:2015-07-29 19:59:28

标签: json nginx reverse-proxy

在网站上,流量通过http传输到位置/实例,我们需要使用SSL和https确保流量安全。当重定向到https时,请求内容类型是“text / xml”,当它实际应该是“application / json”时。我们应该在代理头中明确设置“application / json”吗?我们在http配置中尝试过add_header Content-type“application / json”,但没有什么区别。我们做错了什么?

Http配置:

location /instance {
proxy_pass https://instancehost:9443/instance;
proxy_redirect http://localhost.com https://localhost.com;
proxy_set_header X-xmgr-proxy-domain http://localhost.com:80;
proxy_set_header X-xmgr-proxy /instance;
proxy_set_header Access-Control-Allow-Origin "*";
proxy_set_header Access-Control-Allow-Headers "Origin, X-Requested-With,       Content-Type, Accept";
proxy_ssl_certificate /data/nginx/certs/abc.crt;
proxy_ssl_certificate_key /data/nginx/certs/abc.key;
proxy_ssl_trusted_certificate /etc/pki/tls/certs/abc-bundle.crt;
proxy_ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
proxy_hide_header Content-Type;
add_header Content-type "application/json"
}

在标题中设置内容类型不起作用,因为我们仍然收到204错误。

https配置:

location /instance {
proxy_pass           https://instancehost.com:9443/instance;
proxy_set_header     X-xmgr-proxy-domain https://localhost.com:443;
proxy_set_header     X-xmgr-proxy /instance;
proxy_set_header     Access-Control-Allow-Origin "*";
proxy_set_header     Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
proxy_ssl_certificate /data/nginx/certs/abc.crt;
proxy_ssl_certificate_key /data/nginx/certs/abc.key;

}

1 个答案:

答案 0 :(得分:3)

我认为这里的问题是你做了一个add_header,add_header似乎将这个标题添加到响应中(当请求从后端返回到你的客户端时),并且你想为你的后端设置。

Syntax:     add_header name value [always];
Default:    —
Context:    http, server, location, if in location
Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables. 

你应该在你的conf中这一行

proxy_set_header content-type "application/json";

所有proxy_ *都将为请求设置(从客户端到后端方式)

语法:proxy_set_header字段值; 默认值:

proxy_set_header主机$ proxy_host;

proxy_set_header Connection close;
Context:    http, server, location

Allows redefining or appending fields to the request header passed to the proxied server. The value can contain text, variables, and their combinations. These directives are inherited from the previous level if and only if there are no proxy_set_header directives defined on the current level. By default, only two fields are redefined: