我可以将所有目录请求别名到nginx中的单个文件吗?


9

我试图弄清楚如何在nginx中接收对特定目录的所有请求并返回不带重定向的json字符串。

例:

curl -i http://example.com/api/call1/

预期结果:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: application/json
Date: Fri, 13 Apr 2012 23:48:21 GMT
Last-Modified: Fri, 13 Apr 2012 22:58:56 GMT
Server: nginx
X-UA-Compatible: IE=Edge,chrome=1
Content-Length: 38
Connection: keep-alive

{"logout": true}

到目前为止,我的nginx conf中包含以下内容:

location ~ ^/api/(.*)$ {
    index /api_logout.json;
    alias /path/to/file/api_logout.json;
    types { }
    default_type "application/json; charset=utf-8";
    break;
}

但是,当我尝试发出请求时,Content-Type不粘住:

$ curl -i http://example.com/api/call1/
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: application/octet-stream
Date: Fri, 13 Apr 2012 23:48:21 GMT
Last-Modified: Fri, 13 Apr 2012 22:58:56 GMT
Server: nginx
X-UA-Compatible: IE=Edge,chrome=1
Content-Length: 38
Connection: keep-alive

{"logout": true}

有一个更好的方法吗?我如何才能使应用程序/ json类型保持不变?

编辑:解决方案!

我发现您可以只在return语句中发送手动字符串,所以我做到了这一点,而不是使用别名!

我使用的最终代码:

location /api {
    types { }
    default_type "application/json";
    return 200 "{\"logout\" : true"}";
}

Answers:


2

您可以改用重写来获取全部行为。

location /logout.json {
    alias /tmp/logout.json;
    types {
        application/json json;
    }
}
rewrite ^/api/.* /logout.json;

这不是将您重定向到/logout.json吗?我试图避免发送302重定向响应。
user749618 '04

不,这是内部重写。仅当指定了绝对位置或指定了redirectpermanent标志时,才发送重定向。
mgorven 2012年

0

很简单。整个配置可以是:

# default.conf
# Add file here: /etc/nginx/html/logout.json

server {
  listen 80;
  rewrite ^.*$ /logout.json last;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.