9

I'm trying to figure out how to take all requests made to a particular directory and return a json string without a redirect, in nginx.

Example:

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

Expected result:

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}

Here's what I have so far in my nginx conf:

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

However, when I try to make the request the Content-Type doesn't stick:

$ 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}

Is there a better way to do this? How can I get the application/json type to stick?

EDIT: Solution!

I figured out you can just send manual strings in the return statement, so I did that instead of using aliases!

Final code I used:

location /api {
    types { }
    default_type "application/json";
    return 200 "{\"logout\" : true"}";
}
user749618
  • 193
  • 1
  • 5

2 Answers2

2

You could use a rewrite instead to get the catchall behaviour.

location /logout.json {
    alias /tmp/logout.json;
    types {
        application/json json;
    }
}
rewrite ^/api/.* /logout.json;
mgorven
  • 30,036
  • 7
  • 76
  • 121
  • Doesn't this redirect you to /logout.json? I'm trying to avoid sending a 302 redirect response. – user749618 Apr 14 '12 at 21:19
  • No, that's an internal [rewrite](http://wiki.nginx.org/HttpRewriteModule#rewrite). Redirects are only sent if an absolute location is specified or a `redirect` or `permanent` flag is specified. – mgorven Apr 14 '12 at 21:55
0

Very simple. The whole configuration could be:

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

server {
  listen 80;
  rewrite ^.*$ /logout.json last;
}
user1079877
  • 101
  • 2