Sunday, February 11, 2018

Use curl to test nginx rewrite rules

Be very careful using nginx rewrite. Consider this answer on SO:

The answer author wrote this correct rewrite rule:
location  /foo {
  rewrite /foo/(.*) /$1  break;
  proxy_pass         http://localhost:3200;
  proxy_redirect     off;
  proxy_set_header   Host $host;
}
Which was later edited erroneously:
location  /foo {
  rewrite /foo(.*) /$1  break;
  proxy_pass         http://localhost:3200;
  proxy_redirect     off;
  proxy_set_header   Host $host;
}
That very subtle change causes nginx to redirect, which is undesirable.

This can easily go unnoticed without curl testing:
$ curl -i http://localhost:8080/foo/bar
HTTP/1.1 301 Moved Permanently
Server: nginx/1.13.8
Date: Sun, 11 Feb 2018 14:18:12 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 40
Connection: keep-alive
Location: /bar

<a href="/bar">Moved Permanently</a>.
I've edited the answer back to the original.

Here's a great article about setting up nginx for serving Go apps.

NOTE: you'll need the GVM readme for an up-to-date command to install GVM.