How to configure Nginx to serve multiple static websites on one server

UPDATE: These days you should put your server configurations in files in the /etc/nginx/sites-enabled directory.

As a short note, if you need to configure Nginx to serve multiple static websites out of one nginx.conf file, I have been using this approach, and it seems to work well:

server {
    server_name  www.howisoldmybusiness.com;
    rewrite ^(.*) http://howisoldmybusiness.com$1 permanent;
}

server {
    server_name  howisoldmybusiness.com;
    listen       80;
    location / {
        root /var/www/howisoldmybusiness.com/html;
    }
    access_log  /var/log/nginx/hismb_access.log  main;
    error_log   /var/log/nginx/hismb_error.log  error;
}

The first server configuration says that I want all requests to www.howisoldmybusiness.com to go to howisoldmybusiness.com. I don’t see the need for the “www” part, so this is my way of forward all requests to howisoldmybusiness.com.

The second server configuration block does the real work. It tells Nginx to listen on Port 80 for requests to howisoldmybusiness.com, and when it gets a request it should look in the /var/www/howisoldmybusiness.com/html directory for the files it should server. It also states that all access requests should be logged to the file /var/log/nginx/hismb_access.log using the “main” format, and all errors should be logged to the file /var/log/nginx/hismb_error.log.

The 'main' access_log logging format

I think the main format came with the default Nginx configuration file. You should find it defined in the main http block like this:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

Multiple websites on the same server

If you have Nginx serving up multiple websites on the same server, all you have to do is copy that configuration for the other websites. For instance, I have a website named alaskasquirrel.com on the same server as the howisoldmybusiness.com website, and its configuration is almost identical:

server {
    server_name  www.alaskasquirrel.com;
    rewrite ^(.*) http://alaskasquirrel.com$1 permanent;
}

server {
    server_name  alaskasquirrel.com;
    listen       80;
    location / {
        root /var/www/alaskasquirrel.com/html;
    }
    access_log  /var/log/nginx/aksquirrel_access.log  main;
    error_log   /var/log/nginx/aksquirrel_error.log  error;
}

More information

This is a short blog post, so I’ll leave it at that for now. Here are a few links on configuring Nginx, particularly the Nginx log files:

  • http://nginx.org/en/docs/http/ngx_http_log_module.html
  • https://www.nginx.com/resources/admin-guide/logging-and-monitoring/
  • http://nginx.org/en/docs/ngx_core_module.html#error_log