Michael O.
6min Read

Web servers – NginX Basics

NginX Basics

NginX (pronounced Engine-X or N-Jinx) is a high-performance web server designed to deliver large amounts of content quickly with the efficient use of system resources. NginX’s strong point is its ability to efficiently serve static content, like plain HTML and media files. It is especially good at handling many concurrent connections. Some consider it a less than ideal server for dynamic content. Get a dedicated server.

Like Apache, NginX has one master process and several worker processes. Much like Apache, the main purpose of the master process is to read and evaluate configuration and maintain worker processes which do the actual processing of web requests.

Dynamic content like PHP or CGI is handed off to a secondary handler such as FastCGI or Php-Fpm. In this way, NginX is both simpler to configure (NginX itself has a very simple configuration) and more complex, due to all the handlers that need to be configured as well.

NginX Configuration

The location the main NginX configuration file will vary depending on how you installed the software on your machine. For many distributions, the file will be located at /etc/nginx/nginx.conf.

If it does not exist there, it may also be at /usr/local/nginx/conf/nginx.conf or /usr/local/etc/nginx/nginx.conf.

It is always a good idea to back up this configuration file before changing anything. Also, remember that whenever you make a change to the nginx.conf file, you need to reload your configuration before the change will take effect.

You can do this by issuing the following command:

service nginx reload

Syntax of the NginX Configuration

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

This section would normally not need any editing. Let me explain the syntax.

  • All lines starting with a # (hash) are comments and are not interpreted. These lines are used to explain what a section is for or in this case, to disable a directive as above. This directive can be activated by merely removing the # sign.
  • Settings begin with the variable name and then state an argument or series of arguments separated by spaces. Examples include worker_processes 1; and error_log logs/error.log notice;. All statements end with a semi-colon (;).
  • Some settings, like the events variable above, have arguments that are themselves settings with arguments. All sub-directives are enclosed in one set of curly brackets { }.
  • Brackets are sometimes nested inside each other for multiple sets of sub-directives. If you add or edit a section with nested brackets, make sure they all come in opening and closing pairs.
  • Tabs or multiple spaces are interpreted by nginx as a single space. Using tabs or spaces for indentation in a standardized way will greatly improve the readability of your file and make it easier to maintain.

Using what we have learnt, let us explain the section above again:

  • user – Defines which Linux system user will own and run the nginx server. Most Debian-based distributions use www-data but this may be different in other distros.
  • worker_process – Defines how many threads, or simultaneous instances, of nginx to run.
  • pid – Defines where nginx will write its master process ID or PID. The PID is used by the operating system to keep track of and send signals to the nginx process.

The HTTP section (Global Settings)

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

Most of this will work as is, but note the following:

  • include – The include statement at the beginning of this section includes the file mime.types located at /etc/nginx/mime.types. What this means is that anything written in the file mime.types is interpreted as if it was written inside the http { } block. This lets you include a lengthy amount of information in http { } block without having it clutter up the main configuration file. Includes can also be “wildcarded” as follows:
    include /etc/nginx/sites-enabled/*;    # or  
    include /etc/nginx/conf.d/*.conf;      # more specific for only .conf files 
  • gzip – The gzip directive tells the server to use on-the-fly gzip compression to limit the amount of bandwidth used and speed up some transfers.

Note that the code snippet shown above does not include the closing bracket (}), because the HTTP section isn’t finished.


Virtual Domains

The HTTP block of the nginx.conf file contains the statement include /etc/nginx/sites-enabled/*;. This allows for server block configurations to be loaded in from separate files found in the sites-enabled sub-directory.

Usually these are symlinks to files stored in /etc/nginx/sites-available/. You can quickly enable or disable a virtual server while preserving its configuration file by using symlinks. Nginx provides a single default virtual host file, which can be used as a template to create virtual host files for other domains:

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example.com

We use the server block directive to group a set of instructions or definitions pertaining to a Virtual Domain as follows:

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /usr/share/nginx/html;
        index index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
}

Generally, you’ll want to make a separate file with its own server block for each virtual domain on your server.


Some Useful Directives in the “server” block

  • listen directive, which is located in the server block, tells nginx the hostname/IP and the TCP port where it should listen for HTTP connections. By default, nginx will listen for HTTP connections on port 80.
  • server_name directive, which is located in the server block, lets the administrator provide name-based virtual hosting which allows multiple domains to be served from a single IP address. This name is usually your registered domain name.
  • access_log directive can be set in the http block in nginx.conf or in the server block for a specific virtual domain. It sets the location of the nginx access log. By defining the access log to a different path in each server block, you can sort the output specific to each virtual domain into its own file. An access_log directive defined in the http block can be used to log all access to a single file, or as a catch-all for access to virtual hosts that don’t define their own log files.
  • location setting lets you configure how nginx will respond to requests for resources within the server. Just like the server_name directive tells nginx how to process requests for the domain, such as http://example.com, the location directive covers requests for specific files and folders, such as http://example.com/blog/. A server block may contain multiple location directives. The location block may also specify a different directory by re-declaring the root directive and may also define a new index directive which only matches within that location.

While this is only a small taste of what NginX is capable of, you can also see the following guides:

Happy Hosting!


The Author

Michael O.

Michael is the founder, managing director, and CEO of HOSTAFRICA. He studied at Friedrich Schiller University Jena and was inspired by Cape Town's beauty to bring his German expertise to Africa. Before HOSTAFRICA, Michael was the Managing Director of Deutsche Börse Cloud Exchange AG, one of Germany's largest virtual server providers.

More posts from Michael