Score:1

Nginx config order of operations

cn flag

Apologies if this is answered or documented already but I was confused on this so I'm hoping the community can provide some insight.

The below example is specifically for proxy_pass and proxy_set_header config directives, but my overall question is more of a "How does Nginx config handle ordering in general?" type of question.

I came across some working nginx config, with a location block such as this:

  location / {
    proxy_pass http://internal.example.com/req;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header X-Forwarded-User $auth_resp_x_user;
  }

This confused me since I've always been under the impression that ordering matters, and the headers would need to be set BEFORE the proxy_pass line. Such as this:

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header X-Forwarded-User $auth_resp_x_user;

    proxy_pass http://internal.example.com/req;
  }

Questions:

  • Does the ordering actually matter?
  • If it doesn't matter here, is that specific to proxy_pass? It does matter in other nginx config lines, correct?
  • Is this type of ordering/precedence documented anywhere? (Sorry if it is, I'm not seeing it)

Thank you for any insight and help.

Score:2
us flag

In general, nginx configuration is declarative. This means, every configuration directive has an effect of certain separately defined processing step in handling a request.

This means that in general the order of directives inside a specific scope does not matter.

However, there are exceptions to the general rule:

  • location blocks that match regular expressions are dependent on order. The first matching block is used to process the request.

  • rewrite module processes directives imperatively

The only reference for this fact I could find is in IfIsEvil article.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.