Nginx - can "if" be safely used at the level of a server block?
From "If is Evil":
In some cases, it’s also possible to move ifs to server level (where it’s safe as only other rewrite module directives are allowed within it).
This suggests that if
in a server
block is safe(r) than in a location
block.
One of the first steps when nginx receives a request is evaluating the HTTP Host
header / TLS SNI field, and selecting the virtual host based on the result of that evaluation.
This means that the Host
header is always processed.
Now, if you specify an if
statement for the redirection, it means that the Host
header will be checked twice, first to select the virtual host and then for checking the if
condition. That is twice the work for the processor.
A counter-argument could be the memory consumption for a separate server block. However, the memory allocation is the same for the lifetime of the nginx process, while the double-evaluation of Host
header happens on every request.