Development

How to Configure Nginx

Captain Salem 6 min read

In this tutorial, we are going to over basic configuration of NGINX and tasks that we can accomplish using NGINX. We will discuss concepts such as directives, blocks, directives, Virtual Hosting etc. You should be familiar with Basic concepts of NGINX. If not, check out our tutorials at:

  1. Installing NGINX on Linux

This guide gives a basic introduction to nginx and describes some simple tasks that can be done with it. It is supposed that nginx is already installed on the reader’s machine. If it is not, see the Installing nginx page. This guide describes how to start and stop nginx, and reload its configuration, explains the structure of the configuration file and describes how to set up nginx to serve out static content, how to configure nginx as a proxy server, and how to connect it with a FastCGI application.

What is NGINX ?

Nginx is a lightweight robust and high-performance reverse proxy and web-server developed to accommodate high-traffic web applications.

Among the best features offered by NGINX, one of the useful one is the ability of NGINX to server static content such as HTML files and media files at very high speed. NGINX utilizes asynchronous event-driven models proving high performance under load.

For dynamic content NGINX utilizes CGI - Common Gateway Interface or web servers such as Apache which are then passed back to NGINX and then served to the requesting client.

CGIs are basically protocols that are used for externally interfacing applications back to web servers. They mainly execute as separate processes which are initialized at the start of a request and deleted upon completion.

Nginx Directive, Context and Blocks

Nginx configuration options are known as directives. These directives are organized in groups which are referred to as blocks or contexts.

All NGINX configuration files are located under /etc/nginx directory. By default, Under the NGINX directory, there contains the NGINX configuration file located under /etc/nginx/nginx.conf

In the configuration files, Lines that are preceded by the # sign are known as comments. They are disabled and are not interpreted by NGINX during runtime. All active directives (not preceded by # sign) must be terminated with a semi-colon. If the termination character is missing NGINX fails to load the specified directive and reports an error.

Below is an example of nginx.conf available in the official NGINX repositories -> https://www.nginx.com/resources/wiki/start/topics/examples/full/

user       www www;  ## Default: nobody
worker_processes  5;  ## Default: 1
error_log  logs/error.log;
pid        logs/nginx.pid;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  include    conf/mime.types;
  include    /etc/nginx/proxy.conf;
  include    /etc/nginx/fastcgi.conf;
  index    index.html index.htm index.php;

  default_type application/octet-stream;
  log_format   main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log   logs/access.log  main;
  sendfile     on;
  tcp_nopush   on;
  server_names_hash_bucket_size 128; # this seems to be required for some vhosts

  server { # php/fastcgi
    listen       80;
    server_name  domain1.com www.domain1.com;
    access_log   logs/domain1.access.log  main;
    root         html;

    location ~ \.php$ {
      fastcgi_pass   127.0.0.1:1025;
    }
  }

  server { # simple reverse-proxy
    listen       80;
    server_name  domain2.com www.domain2.com;
    access_log   logs/domain2.access.log  main;

    # serve static files
    location ~ ^/(images|javascript|js|css|flash|media|static)/  {
      root    /var/www/virtual/big.server.com/htdocs;
      expires 30d;
    }

    # pass requests for dynamic content to rails/turbogears/zope, et al
    location / {
      proxy_pass      http://127.0.0.1:8080;
    }
  }

  upstream big_server_com {
    server 127.0.0.3:8000 weight=5;
    server 127.0.0.3:8001 weight=5;
    server 192.168.0.1:8000;
    server 192.168.0.1:8001;
  }

  server { # simple load balancing
    listen          80;
    server_name     big.server.com;
    access_log      logs/big.server.access.log main;

    location / {
      proxy_pass      http://big_server_com;
    }
  }
}

The file above may contain additional information not included upon nginx installation by default. In most cases, NGINX default configurations contains 4 main directives. user, worker_process, error_log and pid

The four directives named above exists outside any particular block and are classified as main block of the configuration. Other blocks such as events, http, server etc. also exist in the main block.

NGINX The HTTP Block

The http block contains directives for handling web traffic. These directives are often referred to as universal because they are passed on to all website configurations NGINX serves. Some of the main directives under the http block include: index, include, default_type, access_log etc. To view the full list of NGINX http block directives, visit the offical NGINX documentation:

http://nginx.org/en/docs/http/ngx_http_core_module.html#directives

NGINX Server Blocks

The http block discussed above contains an include directive which is used to direct NGINX on where the website configuration files are located.

  • For example, if NGINX is installed from the official repo, the include line will point to a path such as /etc/nginx/conf.d/*.conf Note that websites hosted with NGINX should contain standalone configuration files located under /etc/nginx/conf.d with the name pre-formatted with the domain name.conf as csalem.tech.conf Disabled websites should have a .disabled extension as csalem.tech.conf.disabled - This applies to sites that are not served by NGINX.
  • On the other hand, if NGINX is installed from the distribution offical repositories, the include path will point to something like /etc/nginx/sites-enabled/*;. The ../sites-enabled directory contains symbolic links to the sites configuration files which are stored under /etc/nginx/sites-available;. You can disable in the sites-available directory by removing the symbolic link.
  • Although installing nginx from various sources handles configuration differently, an example file is located under /etc/nginx/conf.d/default.conf or /etc/nginx/sites-enables/default.

Regardless of the installation source, server configuration files will contain a server block (or blocks) for a website.

Listening Ports

The listen directive tells NGINX the hostname/IP and the TCP port where it should listen for HTTP connections. The argument default_server means this virtual host will answer requests on port 80 that don’t specifically match another virtual host’s listen statement. The second statement listens over IPv6 and behaves similarly.

Name-based Virtual Hosting

The server_name directive allows multiple domain names to be managed from a single IP address. NGINX automatically decides which domain to server based on the request header recieved. It is recommended to create a file per specified domain to send to the server. For example - This specify that the server should both request for www.domainname.com and domainname.com

server_name www.csalem.tech csalem.tech

You can also pass wildcards to the server_name directive. *.csalem.tech and .csalem.tech both instruct the server to process requests for all subdomains of csalem.tech:

server_name   *.csalem.tech;
server_name   .csalem.tech;

To server all the sites that start with a specific domain. You can set the configuration as shown below:

server_name   csalem.*;

Since NGINX uses the name from the HTTP header recieved to answer requests, you can specify valid domain names or not. NGINX will still answer the request where the domain name is valid.

If the server is hosted on a local network, you can use non-domain hostnames. This functionality can also be applied if you are already familiar with the clients that will be making request to the server.

NGINX Location Blocks

The location directive allows you configure how the server will respond to requests for resources stored within the server. Similar to the server_name directive tells NGINX how to process requests for the domain, location directives cover requests for specific files and folders, such as http://csalem.tech/blog/. Example shown below:

location / { }
location /img/ { }
location /blog/ { }
location /sample/ { }
location /sample/forums/ { }

The locations above are literal string matches, which match any part of an HTTP request that comes after the host segment:

Request: http://domain.com/

Returns: Assuming that there is a server_name entry for domain.com, the location / directive will determine what happens with this request.

NGINX always fulfills requests using the most specific match:

Request: http://csalem.tech/sample/blog/ or http://csalem.tech/sample/blog/about/

Returns: This is fulfilled by the location /sample/blog/ directive because it is more specific, even though location /sample/ also matches this request.

When a location directive is followed by a tilde (~), NGINX performs a regular expression match. These matches are always case-sensitive. So, IndexPage.php would match the first example above, but indexpage.php would not NGINX uses Perl Compatible Regular Expressions (PCRE).

Adding a caret and tilde (^~) to your location directives tells NGINX, if it matches a particular string, to stop searching for more specific matches and use the directives here instead. Other than that, these directives work like the literal string matches in the first group. Even if there’s a more specific match later, if a request matches one of these directives, the settings here will be used. See below for more information about the order and priority of location directive processing.

location = / { }

Finally, if you add an equals sign (=) to the location setting, this forces an exact match with the path requested and then stops searching for more specific matches. For instance, the final example will match only http://example.com/, not http://example.com/index.html. Using exact matches can speed up request times slightly, which can be useful if you have some requests that are particularly popular.

Directives are processed in the following order:

  1. Exact string matches are processed first. If a match is found, NGINX stops searching and fulfills the request.
  2. Remaining literal string directives are processed next. If NGINX encounters a match where the ^~ argument is used, it stops here and fulfills the request. Otherwise, NGINX continues to process location directives.
  3. All location directives with regular expressions (~ and ~*) are processed. If a regular expression matches the request, nginx stops searching and fulfills the request.
  4. If no regular expressions match, the most specific literal string match is used.

Make sure each file and folder under a domain will match at least one location directive. Nested location blocks are not recommended or supported.

Conclusion

That sums about the main configurations of NGINX. Although there some advanced configurations for NGINX, the ones we discussed above hold the main key in ensuring NGINX works effectively. For added features check the official NGINX documentation.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.