5

Im trying to find what is the relation between rewrite statement in nginx location block and set variable statement inside location block. Why im asking is because of different behaviour in below 2 cases

what does not work- getting http 500 as url is not set - when set is after rewrite statement*

location ~ ^/offer/ {
      log_by_lua_file lua/datadog/api_latency.lua;
      proxy_pass $url;
      proxy_read_timeout 60;
      rewrite ^((?U).*)(/?)$ $1  break;
      set $location_name offer;
      set $url https://example.com;
}

What works - when set is before rewrite statement

location ~ ^/offer/ {
      log_by_lua_file lua/datadog/api_latency.lua;
      proxy_pass $url;
      proxy_read_timeout 60;
      set $url https://example.com;
      rewrite ^((?U).*)(/?)$ $1  break;
      set $location_name offer;
}

In the nginx debug logs i can see that set variable being executed in working case but not in non working case. I have searched in nginx documentation if there is any relation - best i can get is that both of these are executed in rewrite phase but no other info regarding cause of this behaviour.

Any idea why this is happening?

1 Answers1

4

From the documentation:

break

stops processing the current set of ngx_http_rewrite_module directives as with the break directive;

Both the rewrite and set directives are implemented by the ngx_http_rewrite_module.

The statements are evaluated sequentially within the location block. The break (either on its own, or part of a rewrite...break) will stop processing within the current context. So any set directives following it will be ignored.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • will any other flag like last/permanant etc solve the case where set directive is not impacted by ordering of statements.? I'm searching the same in the documents as well. – palash kulshreshtha Oct 29 '20 at 09:03
  • Adding any flag to a `rewrite` statement will stop the processing of subsequent rewrite module statements within the current context. Have you tried not adding a flag? – Richard Smith Oct 29 '20 at 09:27