1

For each website I host with nginx, I have got a different file which holds the server {} block in /etc/nginx/conf.d/

For example...
/etc/nginx/conf.d/website1.co.uk
/etc/nginx/conf.d/website2.org
/etc/nginx/conf.d/website3.com

I find myself repeating the same code in every server {} block and was wondering if it is possible to make a "catch all" server {} block to house the reusable code.

This new "catch all" file would include things such as...

# Redirect all www. attempts to non-www.
server {
  server_name www.$anything; hmm?
  return 301 $scheme://$hostname$request_uri;
}

server {
  server_name _; hmm?

  # Add expires to static files
  location ~* \.(?:ico|css|js|gif|jpe?g|png|bmp)$ {
    expires max;
    access_log off;
  }

  # Pass PHP files to PHP
  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
  }

}

Has anyone does this before?
Do we have to repeat these types of generic codes for each website we host?

2
  • 1
    I haven't actually tested this, but I know that the nginx server_name accepts regular expressions if the value starts with a ~. For your non-www example, say, you should be able to use server_name "~^[^w]{3}.*$". More documentation is available here: nginx.org/en/docs/http/server_names.html#regex_names Commented Apr 11, 2013 at 19:17
  • 1
    I regret to inform you of two things: regular expressions are extremely heavy on nginx, and it's usually worth having multiple PHP-FPM pools - and therefore multiple PHP location blocks. Generate them using a script - so much more feature-rich! Commented Apr 11, 2013 at 20:15

1 Answer 1

1

All you need is include. Put all boilerplate in separate files, without server blocks. include fastcgi_params mentioned in the sample config is a prime example. Without a leading slash, nginx will look in the directory where the main configuration file is. So:

include fastcgi_params;
include /etc/nginx/fastcgi_params;

are equivalent, if nginx.conf is in /etc/nginx.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the advice, I think I may have to use this approach. Could you explain your last sentence a little more please
He means include relative paths start at the directory containing nginx.conf. So if your nginx.conf is /etc/nginx/nginx.conf, include considers /etc/nginx/ its PWD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.