Clarkey
Clarkey

Reputation: 708

nginx - How do I make server-wide configuration for every hosted website

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?

Upvotes: 1

Views: 880

Answers (1)

user1600649
user1600649

Reputation:

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.

Upvotes: 1

Related Questions