2

I keep reading that in nginx config files, we should hardcode hostnames instead of using variables.

For example:

server_name www.example.com example.com;
return 301 https://www.example.com$request_uri;

instead of

server_name www.example.com example.com;
return 301 https://$host$request_uri;

I find it surprising that nginx wouldn't cache static config upon start.

Is there official documentation about this somewhere, or is it just anecdotal?

  • The two statements perform different functions. $host is not a static variable but based on the headers in the original request. If you only host one website, then hardcoding the website name is not an issue, but if you host many websites, you may require a flexible configuration that does not contain the name example.com. – Richard Smith Oct 11 at 10:34
  • @RichardSmith Point taken I updated the text, I was struggling to find a good example. The question is about the hardcoding itself, I'm not sure if the example is a good one. – lonix Oct 11 at 11:07
  • Your second example will not work correctly as you risk redirection to www.www.example.com. – Richard Smith Oct 11 at 11:26
  • @RichardSmith Lol updated again. – lonix Oct 11 at 11:44
  • 1
    Maybe the articles in which you "keep reading" about this have examples? Could you link a few, so we can review their claims directly? – ceejayoz Oct 11 at 13:52
0

I found official documentation.

It refers to variables in general, but the sentiment is clear: hardcode if possible.

Variables should not be used as template macros. Variables are evaluated in the run-time during the processing of each request, so they are rather costly compared to plain static configuration. Using variables to store static strings is also a bad idea. Instead, a macro expansion and "include" directives should be used to generate configs more easily and it can be done with the external tools, e.g. sed + make or any other common template mechanism.

There is also this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.