Linode Library Home
Linode Library RSS Feed
Home :: Web Servers :: Nginx :: Configuration
Print View View Source

Basic Nginx Configuration

Published: by

nginx is a lightweight, high performance web server designed to deliver large amounts of static content quickly with efficient use of system resources. nginx's strong point is its ability to efficiently serve static content, like plain HTML and media files. Some consider it a less than ideal server for dynamic content.

Looking under the hood, unlike Apache, which uses a threaded or process-oriented approach to handle requests, nginx uses an asynchronous event-driven model which provides more predictable performance under load. Rather than using the embedded interpreter approach, nginx hands off dynamic content to CGI, FastCGI, or even other web severs like Apache, which is then passed back to nginx for delivery to the client.

This leads to a more complex setup for certain deployments. For these and other reasons, the configuration of nginx can feel complicated and unintuitive at first. This document aims to de-mystify nginx configuration by familiarizing you with basic nginx parameters and conventions. We'll be going through nginx's primary configuration file.

All nginx configuration files are located in the /etc/nginx/ directory. The primary configuration file is /etc/nginx/nginx.conf.

Note

This is where the files will be located if you install nginx from the package manager. Other possible locations include /opt/nginx/conf/.

Contents

Prerequisites

Before we begin, make sure you have completed the following:

If you're new to Linux server administration, you may also be interested in our Using Linux document series, including the Beginner's Guide and Administration Basics Guide.

Before You Start: Preserve a Working Configuration

Sometimes, server configuration files can get so corrupted or convoluted that they become unusable, so it's always a good idea to have a working copy of the essential files on hand. Fortunately, nginx makes a certain level of restoration very easy. All of the configuration files come with a backup copy named with a .default. Leave these alone. That way, if you need to revert back to a working configuration at some point, you'll be able to copy the default files and start over. For example, you could restore the nginx.conf.default file if your nginx.conf file ever became unsalvageable.

For even better restoration options, we recommend making regular backups of your nginx configuration. You might want to store your entire /etc/nginx/ directory in a git repository so you can save the original settings and all the versions from all your different changes. Another option is to periodically create dated copies of your files. You can accomplish this by issuing the following command, and modifying the date specified as needed:

cp /opt/nginx/conf/nginx.conf /opt/nginx/conf/nginx.conf-20100102

Reload after Changes

Now you're ready to make changes to your nginx configuration. 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:

/etc/init.d/nginx reload

Introduction to Syntax

This section showcases an excerpt from the beginning of the default configuration file, /etc/nginx/nginx.conf:

File excerpt:nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

Normally, you will not need to change anything in this first section. Instead, we'll use this as an opportunity to explain the syntax of the configuration file.

HTTP (Universal Configuration)

The next section of the nginx.conf file covers the universal directives for nginx as it handles HTTP web traffic. The first part of the HTTP block is shown below:

File excerpt:nginx.conf

http {
    include       mime.types;
    default_type  application/octet-stream;

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

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

Most of the http { } block should work as-is for most nginx configurations. We do, however, want to draw your attention to the following configuration options:

File excerpt:nginx.conf

        gzip on;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types    text/plain text/html text/css
                      application/x-javascript text/xml
                      application/xml application/xml+rss
                      text/javascript;

Note

If you enable gzip compression here, note that you will be trading increased CPU costs in exchange for your lower bandwidth use. Set the gzip_comp_level to a value between 1 and 9, where 9 requires the greatest amount of CPU resources and 1 requires the least. The default value is 1.

Note that the code snippet shown above does not include the closing bracket (}), because the HTTP section isn't finished. This block is concluded in the next section.

Server (Virtual Domains Configuration)

The HTTP block of the nginx.conf file contains the server variable, which has its set of variables in a nested block that is opened and closed with its own brackets:

File excerpt:nginx.conf

        server {
                listen       80;
                server_name  localhost;

                access_log  logs/localhost.access.log  main;

                location / {
                    root   html;
                    index  index.html index.htm;
                }
        }
}

Note

The http { } block concludes at the end of the above example.

The server block is where the typical nginx user will make most of his or her changes to the default configuration. Generally, you'll want to make one server block per virtual domain on your server. More configuration options for the server are shown in the following sections.

Listening Ports

The 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.

Next we'll present a few common examples for the listen directive.

Note

You can use more than one listen directive, if needed.

File excerpt:nginx.conf

listen     127.0.0.1:80;
listen     localhost:80;

These two examples direct nginx to listen on 127.0.0.1; that is, the local loopback interface. localhost is conventionally set as the hostname for 127.0.0.1 in /etc/hosts.

File excerpt:nginx.conf

listen     127.0.0.1:8080;
listen     localhost:8080;

The second pair of examples also listen on localhost, but they listen for responses on port 8080 instead of port 80.

File excerpt:nginx.conf

listen     192.168.3.105:80;
listen     192.168.3.105:8080;

The third pair of examples specify a server listening for requests on the IP address 192.168.3.105. The first listens on port 80 and the second on port 8080.

File excerpt:nginx.conf

listen     80;
listen     *:80;
listen     8080;
listen     *:8080;

The fourth set of examples tell nginx to listen on all domains and IP addresses on a specific port. listen 80; is equivalent to listen *:80;, and listen 8080; is equivalent to listen *:8080;.

File excerpt:nginx.conf

listen     12.34.56.77:80;
listen     12.34.56.78:80;
listen     12.34.56.79:80;

Finally, the last set of examples instruct the server to listen for requests on port 80 for the IP addresses 12.34.56.77, 12.34.56.78, and 12.34.56.79.

Name-Based Virtual Hosting

The server_name directive, which is located in the server block, lets the administrator provide name-based virtual hosting. This allows multiple domains to be served from a single IP address. The server decides which domain to serve based on the request header it receives (for example, when someone requests a particular URL).

Typically, you will want to create one server block per domain you want to host on your server, and the server_name directive is where you specify that domain.

Next we'll present a few common examples for the server_name directive:

File excerpt:nginx.conf

server_name   example.com;

The example above directs nginx to process requests for example.com. This is the most basic configuration.

File excerpt:nginx.conf

server_name   example.com www.example.com;

The second example instructs the server to process requests for both example.com and www.example.com.

File excerpt:nginx.conf

server_name   *.example.com;
server_name   .example.com;

These two examples are equivalent. *.example.com and .example.com both instruct the server to process requests for all subdomains of example.com, including www.example.com, foo.example.com, etc.

File excerpt:nginx.conf

server_name   example.*;

The fourth example instructs the server to process requests for all domain names beginning with example., including example.com, example.org, example.net, example.foo.com, etc.

File excerpt:nginx.conf

server_name   example.com linode.com icann.org;

The fifth example instructs the server to process requests for three different domain names. Note that any combination of domain names can be listed in a single server_name directive.

File excerpt:nginx.conf

server_name   localhost linode galloway;

nginx allows you to specify names for virtual hosts that are not valid domain names. nginx uses the name from the HTTP header to answer requests; it doesn't matter to nginx whether the domain name is valid or not. In this case, the hostames can be specified in the /etc/hosts file.

Using non-domain hostnames may be useful if your nginx server is deployed on a LAN, or if you already know all of the clients that will be making requests of the server. This includes front-end proxy servers that preconfigured /etc/hosts entries for the IP address on which nginx is listening.

File excerpt:nginx.conf

server_name   "";

Finally, if you set server_name to the empty quote set (""), nginx will process all requests that either do not have a hostname, or that have an unspecified hostname, such as requests for the IP address itself.

Note

Individual names are separated with a space. You can use regular expressions if desired.

Access Logs

The access_log directive, which is located in the server block, sets the location of the nginx access log. You can use a path relative to the current directory (most likely /etc/nginx/):

File excerpt:nginx.conf

access_log logs/example.access.log;

Or, you can use a full path:

File excerpt:nginx.conf

access_log /srv/http/example.com/logs/access.log;

You can also disable the access log, although this is not recommended:

File excerpt:nginx.conf

access_log off;

Location (File and Folder Configuration)

The final component of the server settings block is the location directive. We'll cover the specifics of what goes inside of a location block in the next section; right now we're going to focus on the basic path setting.

The 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/.

Note

You can have more than one location directive.

Here are a few examples:

File excerpt:nginx.conf

location / { }
location /images/ { }
location /blog/ { }
location /planet/ { }
location /planet/blog/ { }

These first five examples are literal string matches, which match any part of an HTTP request that comes after the host segment. So, for example, if someone requests:

Request: http://example.com/

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

nginx always fulfills request using the most specific match. So, for example:

Request: http://example.com/planet/blog/ or http://example.com/planet/blog/about/

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

File excerpt:nginx.conf

location ~ IndexPage\.php$ { }
location ~ ^/BlogPlanet(/|/index\.php)$ { }

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. In the second example, the regular expression ^/BlogPlanet(/|index\.php)$ will match requests for /BlogPlanet/ and /BlogPlanet/index.php, but not /BlogPlanet, /blogplanet/, or /blogplanet/index.php. Nginx uses Perl Compatible Regular Expressions (PCRE).

File excerpt:nginx.conf

location ~* \.(pl|cgi|perl|prl)$ { }
location ~* \.(md|mdwn|txt|mkdn)$ { }

If you want matches to be case-insensitive, use a tilde with an asterisk (~*). The examples above all specify how nginx should process requests that end in a particular file extension. In the first example, any file ending in: .pl, .PL, .cgi, .CGI, .perl, .Perl, .prl, and .PrL (among others) will match the request.

File excerpt:nginx.conf

location ^~ /images/IndexPage/ { }
location ^~ /blog/BlogPlanet/ { }

Adding a caret and tilde (^~) to your location directives tells nginx, if it makes a match for 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. So, 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.

File excerpt:nginx.conf

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.

Note

While nginx's configuration parser is technically capable of reading nested location blocks, this is neither recommended nor supported.

Location Root and Index

The location setting is another variable that has its own block of arguments.

Once nginx has determined which location directive best matches a given request, the response to this request is determined by the contents of the associated location directive block. Here's an example:

File excerpt:nginx.conf

location / {
    root   html;
    index  index.html index.htm;
}

In this example, the document root is located in the html/ directory. Given the default installation prefix for nginx, the full path to this location is /etc/nginx/html/.

Request: http://example.com/blog/includes/style.css,

Returns: nginx will attempt to serve the file located at /etc/nginx/html/blog/includes/style.css.

Note

You can use absolute paths for the root directive if desired.

The index variable tells nginx which file to serve if none is specified. For example:

Request: http://example.com

Returns: nginx will attempt to serve the file located at /etc/nginx/html/index.html.

If multiple files are specified for the index directive, nginx will process the list in order and fulfill the request with the first file that exists. If index.html doesn't exist in the relevant directory, then index.htm will be used. If neither exist, a 404 message will be sent.

Here's a more complex example, showingcasing a set of location directives take approximately from the Nginx and Perl-FastCGI Guide for a server responding for the domain example.com:

File excerpt:nginx.conf location directive

location / {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}

location ~ \.pl$ {
    gzip off;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/var/run/fcgiwrap.socket;
    fastcgi_index index.pl;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
}

In this example, all requests for resources that end in a .pl extension are handled by the second location block, which specifies a fastcgi handler for these requests. Otherwise, nginx uses the first location directive. Resources are located on the file system at /srv/www/example.com/public_html/. If no file name is specified in the request, nginx will look for and provide the index.html or index.htm file. If no index files are found, the server will return a 404 error.

Let's analyze what happens during a few requests:

Request: http://example.com/

Returns: /srv/www/example.com/public_html/index.html if it exists. If that file doesn't exist, it will serve /srv/www/example.com/public_html/index.htm. If neither exists, nginx returns a 404 error.

Request: http://example.com/blog/

Returns: /srv/www/example.com/public_html/blog/index.html if it exists. If that file doesn't exist, it will serve /srv/www/example.com/public_html/blog/index.htm. If neither exists, nginx returns a 404 error.

Request: http://example.com/tasks.pl

Returns: nginx will use the FastCGI handler to execute the file located at /srv/www/example.com/public_html/tasks.pl and return the result.

Request: http://example.com/squire/roster.pl

Returns: nginx will use the FastCGI handler execute the file located at /srv/www/example.com/public_html/squire/roster.pl and return the result.

Best Practices

The examples and explanations in the previous sections should help you learn to configure your nginx server with elegance and confidence. In this section, we'll look at a few best practices for keeping your nginx configuration organized:

File excerpt:/etc/nginx/nginx.conf

http {
      # [...]

      include /srv/www/example.com/nginx.conf;

      # [...]
}

Note

You can also use a relative path, if desired.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

Creative Commons License

This guide is licensed under a Creative Commons Attribution-NoDerivs 3.0 United States License.

Last edited by Sharon Campbell on Friday, July 26th, 2013 (r3561).