nginx,

nginx: [emerg] "if" directive is not allowed here

Jan 17, 2023 · 1 min read · Post a comment

While I was trying to introduce some Nginx conditional for an “obscure” reason, I attempt reloading the config, so the changes could apply, I’ve received the following error in the CLI: nginx: [emerg] "if" directive is not allowed here in /etc/nginx/conf.d/<some_site_name>.conf:27.

Prerequisites

  • Nginx

Solution

The if statement can only be part of the server and location blocks. Also, using if in location setting is strongly discouraged and considered “evil”. And why is that so?

if being part of the rewrite module, assess operations in an imperative way. On the flip side, the Nginx configuration mainly is declarative.

  • Imperative is all about you describing the steps to get to the desired state.
  • Declarative is describing the final desired state and let the application, tool to work out the rest.

Conclusion

Related post: Declarative vs Imperative Infrastructure as Code.

Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.