nginx server tutorials (installation, configuration, performance tuning, security)
what is nginx?
Nginx is an open source reverse proxy server for HTTP, HTTPS, SMTP, POP3, and IMAP protocols, as well as a load balancer, HTTP cache, and a web server. The nginx project started with a strong focus on high concurrency, high performance and low memory usage.
Installation
Configuration
Performance tuning
Enable fastcgi
Dynamic Module installation google pagespeed module
Use Nginx as reverse proxy for apache
SSL Installation
Installing NGINX WAF (Security)
nginx as reverse proxy
load balancing on nginx server
Downloading and Installing Nginx
Depending on the optional modules that you select at compile time, you will perhaps need different prerequisites. You will be guided through the process of installing the most common ones, such as GCC, PCRE, zlib, and OpenSSL.
Note
If your operating system offers the possibility to install the Nginx package from a repository, and you are confident enough that the available version will suit all of your needs with the modules included by default, you could consider skipping this chapter altogether and simply run one the following commands.
apt-get install nginx
For Red Hat–based operating systems, use the following command:
yum install nginx
Alternatively, you can download and install prebuilt packages from the official Nginx website at http://www.nginx.org.
download build tools for installation from source but nginx alawas per compiles for you at their official website.
yum install pcre pcre-devel
[root@example.com ~]# yum groupinstall “Development Tools”
If you use apt-get to install software packages, run the following command:
[root@example.com ~]# apt-get install build-essentials
[root@example.com ~]# apt-get install libpcre3 libpcre3-dev
[root@example.com ~]# apt-get install zlib1g zlib1g-dev
[root@example.com ~]# yum install zlib zlib-devel
[root@example.com ~]# yum install openssl openssl-devel
If using apt-get, run the following command:
[root@example.com ~]# apt-get install openssl openssl-de
GNU Compiler Collection (GCC)
There are currently 2 version branches of the project:
Stable version: This version is usually recommended, as it is approved by both developers and users, but is usually a little behind the mainline version in terms of bug fixes and features.
Mainline version: This is the latest version available for download and comes with the newest developments and bug fixes. It was formerly known as the development version.
Downloading and extracting
Once you have made your choice about which version you will be using, head over to http://www.nginx.org and find the URL of the file you wish to download. Position yourself in your home directory, which will contain the source code to be compiled, and download the file using wget:
[alex@example.com ~]$ mkdir src && cd src
[alex@example.com src]$ wget http://nginx.org/download/nginx-1.8.0.tar.gz
We will be using version 1.8.0, the latest stable version as of April, 2015. Once downloaded, extract the archive contents in the current folder:
[alex@example.com src]$ tar zxf nginx-1.8.0.tar.gz
You have successfully downloaded and extracted Nginx. Now, the next step will be to configure the compilation process in order to obtain a binary that perfectly fits your operating system.
Configure options
There are usually three steps when building an application from source: the configuration, the compilation, and the installation. The configuration step allows you to select a number of options that will not be editable after the program is built, as it has a direct impact on the project binaries. Consequently, it is a very important stage that you need to follow carefully if you want to avoid surprises later, such as the lack of a specific module or having configuration files located in a random folder.
The process consists of appending certain switches to the configure command that comes with the source code. The three types of switches that you can activate will be covered later, but let’s first study the easiest way to proceed.
The easy way
If, for some reason, you do not want to bother with the configuration step, such as for testing purposes or simply because you will be recompiling the application in the future, you may simply use the configure command with no switches. Execute the following three commands to build and install a working version of Nginx, starting with the configure command:
[alex@example.com nginx-1.8.0]# ./configure
Running this command should initiate a long procedure of verifications to ensure that your system contains all of the necessary components. If the configuration process fails, check the prerequisites section again, as it is the most common cause of errors. For information about why the command failed, you may also refer to the objs/autoconf.err file, which provides a more detailed report. The make command will compile the application. This step should not cause any errors as long as the configuration went fine.
[alex@example.com nginx-1.8.0]# make [root@example.com nginx-1.8.0]# make install
This last step will copy the compiled files as well as other resources to the installation directory, by default, /usr/local/nginx. You may need to be logged in as root to perform this operation, depending on permissions granted to the /usr/local directory.
Again, if you build the application without configuring it, you take the risk of missing out on a lot of features, such as the optional modules and others that we are about to discover.
Path options
When running the configure command, you are offered the possibility to enable some switches that let you specify the directory or file paths for a variety of elements. Note that the options offered by the configuration switches may change according to the version you downloaded. The options listed below are valid with the stable version, as of release 1.8.0. If you use another version, run the ./configure –help command to list the available switches for your setup.
Using a switch typically consists of appending some text to the command line, for instance, using the –conf-path switch:
[alex@example.com nginx-1.8.0]# ./configure –conf- path=/etc/nginx/nginx.conf
Here is an exhaustive list of the configuration switches for configuring paths:
Switch |
Usage |
Default Value |
–prefix=… |
The base folder in which Nginx will be installed. |
/usr/local/nginx Note: If you configure other switches using relative paths, they will connect to the base folder. For example, specifying –conf- path=conf/nginx.conf will result in your configuration file being found at /usr/local/nginx/conf/nginx.conf. |
–sbin-path=… |
The path where the Nginx binary file should be installed. |
<prefix>/sbin/nginx. |
–conf-path=… |
The path of the main configuration file. |
<prefix>/conf/nginx.conf. |
–error-log-path=… |
The location of your error log. Error logs can be configured very accurately in the configuration files. This path only applies in case you do not specify any error logging directive in your configuration. |
<prefix>/logs/error.log. |
–pid-path=… |
The path of the Nginx pid file. You can specify the pid file path in the configuration file. If that’s not the case, the value you specify for this switch will be used. |
<prefix>/logs/nginx.pid. Note: The pid file is a simple text file containing the process identifier. It is placed in a predefined location so that other applications can easily find the pid of a running program. |
–lock-path=… |
The location of the lock file. Again, it can be specified in the configuration file, but if it isn’t, this value will be used. |
<prefix>/logs/nginx.lock. Note: The lock file allows other applications to determine whether or not the program is running. In the case of Nginx, it is used to make sure that the process is not started twice. |
–with- perl_modules_path=… |
Defines the path to the Perl modules. This switch must be defined if you want to include additional Perl modules. |
|
–with-perl=… |
Path to the Perl binary file; used to execute Perl scripts. This path must be set if you want to allow execution of Perl scripts. |
|
–http-log-path=… |
Defines the location of the access logs. This path is used only if the access log directive is unspecified in the configuration files. |
<prefix>/logs/access.log. |
–http-client-body- temp-path=… |
Directory used for storing temporary files generated by client requests. |
<prefix>/client_body_temp. |
–http-proxy-temp- path=… |
Location of the temporary files used by the proxy. |
<prefix>/proxy_temp. |
–http-fastcgi- temp-path=… –http-uwsgi-temp- path=… –http-scgi-temp- path=… |
Location of the temporary files used by the HTTP FastCGI, uWSGI, and SCGI modules. |
Respectively <prefix>/fastcgi_temp, <prefix>/uwsgi_temp, and <prefix>/scgi_temp. |
–builddir=… |
Location of the application build. |
:
Module options
Modules, which will be detailed in Chapter 4, Module Configuration, need to be selected before compiling the application. Some are enabled by default and some need to be enabled manually, as you will see in the following table.
Modules enabled by default
The following switches allow you to disable modules that are enabled by default:
Modules enabled by default |
Description |
–without-http_charset_module |
Disables the Charset module to re-encode web pages. |
–without-http_gzip_module |
Disables the Gzip compression module. |
–without-http_ssi_module |
Disables the Server Side Include module. |
–without-http_userid_module |
Disables the User ID module providing user identification via cookies. |
–without-http_access_module |
Disables the Access module allowing access configuration for IP address ranges. |
–without- http_auth_basic_module |
Disables the Basic Authentication module. |
–without-http_autoindex_module |
Disables the Automatic Index module. |
–without-http_geo_module |
Disables the Geo module allowing you to define variables depending on IP address ranges. |
–without-http_map_module |
Disables the Map module that allows you to declare map blocks. |
–without-http_referer_module |
Disables the Referer control module. |
–without-http_rewrite_module |
Disables the Rewrite module. |
–without-http_proxy_module |
Disables the Proxy module to transfer requests to other servers. |
–without-http_fastcgi_module –without-http_uwsgi_module –without-http_scgi_module |
Disables the FastCGI, uWSGI, or SCGI modules to interact with FastCGI, uWSGI, or SCGI processes respectively. |
–without-http_memcached_module |
Disables the Memcached module to interact with the memcache daemon. |
–without- http_limit_conn_module |
Disables the Limit Connections module to restrict resource usage according to defined zones. |
–without-http_limit_req_module |
Disables the Limit Requests module allowing you to limit the number of requests per user. |
–without-http_empty_gif_module |
Disables the Empty GIF module to serve a blank GIF image from memory. |
–without-http_browser_module |
Disables the Browser module to interpret the User Agent string. |
–without- http_upstream_ip_hash_module |
Disables the Upstream IP Hash module providing the ip_hash directive in upstream blocks. |
–without- http_upstream_least_conn_module |
Disables the Upstream Least Conn module providing the least_conn directive in upstream blocks. |
–without- http_split_clients_module |
Disables the Split Clients module |
Modules disabled by default
The following switches allow you to enable modules that are disabled by default:
Modules disabled by default |
Description |
–with-http_ssl_module |
Enables the SSL module to serve pages over HTTPS. |
–with- http_realip_module |
Enables the Real IP module to read the real IP address from the request header data. |
–with- http_addition_module |
Enables the Addition module, which lets you append or prepend data to the response body. |
–with-http_xslt_module |
Enables the XSLT module to apply XSL transformations to XML documents. Note: You will need to install the libxml2 and libxslt libraries on your system if you wish to compile these modules. |
–with- http_image_filter_module |
Enables the Image Filter module that lets you apply modification to images. Note: You will need to install the libgd library on your system if you wish to compile this module. |
–with-http_geoip_module |
Enables the GeoIP module to achieve geographic localization using MaxMind’s GeoIP binary database. Note: You will need to install the libgeoip library on your system if you wish to compile this module. |
–with-http_sub_module |
Enables the Substitution module to replace text in web pages. |
–with-http_dav_module |
Enables the WebDAV module (Distributed Authoring and Versioning via Web). |
–with-http_flv_module |
Enables the FLV module for special handling of .flv (Flash video) files. |
–with-http_mp4_module |
Enables the MP4 module for special handling of .mp4 video files. |
–with- http_gzip_static_module |
Enables the Gzip Static module to send pre-compressed files. |
–with- http_random_index_module |
Enables the Random Index module to pick a random file as the directory index. |
–with- http_secure_link_module |
Enables the Secure Link module to check the presence of a keyword in the URL. |
–with- http_stub_status_module |
Enables the Stub Status module, which generates a server statistics and information page. |
–with- google_perftools_module |
Enables the Google Performance Tools module. |
–with- http_degradation_module |
Enables the Degradation module that controls the behavior of your server depending on current resource usage. |
–with-http_perl_module |
Enables the Perl module, allowing you to insert Perl code directly into your Nginx configuration files and to make Perl calls from SSI. |
–with-http_spdy_module |
Enables the SPDY module allowing clients to communicate with Nginx over the SPDY protocol. |
–with- http_gunzip_module |
Enables the Gunzip module, which offers to decompress a gzip-encoded response from a backend server before forwarding it to the client. |
–with- http_auth_request_module |
Enables the Auth Request module. This module allows you to delegate the HTTP authentication mechanism to a backend server via a subrequest. The status code of the response can be stored in a variable. |
Miscellaneous options
Other options are available in the configuration script, for example, regarding the mail server proxy feature or event management. These have been enlisted as follows:
Mail server proxy options |
Description |
–with-mail |
Enables mail server proxy module. Supports POP3, IMAP4, SMTP. It is disabled by default. |
–with- mail_ssl_module |
Enables SSL support for the mail server proxy. It is disabled by default. |
–without- mail_pop3_module |
Disables the POP3 module for the mail server proxy. It is enabled by default when the mail server proxy module is enabled. |
–without- mail_imap_module |
Disables the IMAP4 module for the mail server proxy. It is enabled by default when the mail server proxy module is enabled. |
–without- mail_smtp_module |
Disables the SMTP module for the mail server proxy. It is enabled by default when the mail server proxy module is enabled. |
Event management: |
Allows you to select the event notification system for the Nginx sequencer. For advanced users only. |
–with- rtsig_module |
Enables the rtsig module to use rtsig as event notification mechanism. |
–with- select_module |
Enables the select module to use select as event notification mechanism. By default, this module is enabled unless a better method is found on the system—kqueue, epoll, rtsig, or poll. |
–without- select_module |
Disables the select module. |
–with- poll_module |
Enables the poll module to use poll as event notification mechanism. By default, this module is enabled if available, unless a better method is found on the system—kqueue, epoll, or rtsig. |
–without- poll_module |
Disables the poll module. |
User and group options |
Description |
–user=… |
Default user account to start the Nginx worker processes. This setting is used only if you do not specify the user directive in the configuration file. |
–group=… |
Default user group to start the Nginx worker processes. This setting is used only if you do not specify the group directive in the configuration file. |
Other options |
Description |
–with-ipv6 |
Enables IPv6 support. |
–without- http |
Disables the HTTP server. |
–without- http-cache |
Disables HTTP caching features. |
–add- module=PATH |
Adds a third-party module to the compile process by specifying its path. This switch can be repeated indefinitely if you wish to compile multiple modules. |
–with-debug |
Enables additional debugging information to be logged. |
–with-file- aio |
Enables support for AIO (Asynchronous IO disk operations). |
Configuration examples
Here are a few examples of configuration commands that may be used for various cases. In these examples, the path switches have been omitted, as they are specific to each system and leaving the default values may simply function correctly.
Note
Be aware that these configurations do not include additional third-party modules. Please refer to Chapter 4, Module Configuration, for more information about installing add-ons.
About the prefix switch
During the configuration, you should take particular care of the –prefix switch. Many of the future configuration directives (that will be approached in further chapters) will be based on the path you select at this point. While it is not a definitive problem since absolute paths can still be employed, you should know that the prefix cannot be changed once the binaries have been compiled.
There is also another issue that you may run into if you plan to keep up with the times and update Nginx as new versions are released. The default prefix (if you do not override the setting by using the –prefix switch) is /usr/local/nginx. This is a path that does not include the version number. Consequently, when you upgrade Nginx, if you do not specify a different prefix, the new install files will override the previous ones, which among other problems, could potentially erase your currently running binaries.
It is thus recommended to use a different prefix for each version you will be using. Use the following command to specify a prefix that is specific to version 1.8.0:
./configure –prefix=/usr/local/nginx-1.8.0
Additionally, to make future changes simpler, you may create a symbolic link
/usr/local/nginx pointing to /usr/local/nginx-1.8.0. Once you upgrade, you can update the link to make it point to /usr/local/nginx-newer.version. This will allow the init script to always make use of the latest installed version of Nginx.
Regular HTTP and HTTPS servers
The first example describes a situation where the most important features and modules to serve HTTP and HTTPS content are enabled, and the mail-related options are disabled:
./configure –user=www-data –group=www-data –with-http_ssl_module –with- http_realip_module
As you can see, the command is rather simple and most switches have been left out. The reason for this is that the default configuration is rather efficient, and most of the important modules are enabled. You will only need to include the http_ssl module to serve HTTPS content, and optionally, the real IP module to retrieve your visitors’ IP addresses in case you are running Nginx as backend server.
All modules enabled
The next situation includes all available modules, and it is up to you whether you want to use them or not at runtime:
./configure –user=www-data –group=www-data –with-http_ssl_module –with- http_realip_module –with-http_addition_module –with-http_xslt_module — with-http_image_filter_module –with-http_geoip_module –with- http_sub_module –with-http_dav_module –with-http_flv_module –with- http_mp4_module –with-http_gzip_static_module –with- http_random_index_module –with-http_secure_link_module –with- http_stub_status_module –with-http_perl_module –with- http_degradation_module –with-http_spdy_module –with-http_gunzip_module –
-with-http_auth_request_module
Build configuration issues
In some cases, the configure command may fail—after a long list of checks, you may receive a few error messages on your terminal. In most (if not all) cases, these errors are related to missing prerequisites or unspecified paths.
In such cases, proceed with the following verifications carefully to make sure you have all it takes to compile the application, and optionally, consult the objs/autoconf.err file for more details about the compilation problem. This file is generated during the configure process and will tell you exactly which part of the process failed.
Make sure you installed the prerequisites
There are basically four main prerequisites: GCC, PCRE, zlib, and OpenSSL. The last three are libraries that must be installed in two packages: the library itself and its development sources. Make sure you have installed both for each of them. Refer to the prerequisites section at the beginning of this chapter for additional information. Note that other prerequisites such as LibXML2 or LibXSLT may be required to enable extra modules (for example, in the case of the HTTP XSLT module).
If you are positive that all of the prerequisites were installed correctly, perhaps the issue comes from the fact that the configure script is unable to locate the prerequisite files. In that case, make sure that you include the configuration switches related to file paths, as described earlier.
For example, the following switch allows you to specify the location of the OpenSSL library files:
./configure […] –with-openssl=/usr/lib64
The OpenSSL library file will be looked for in the specified folder.
Directories exist and must be writable
Always remember to check the obvious; everyone makes even the simplest of mistakes sooner or later. Make sure that the directory you placed the Nginx files in has read and write permissions for the user running the configuration and compilation scripts. Also ensure that all paths specified in the configure script switches are existing, valid paths.
Compiling and installing the program
The configuration process is of utmost importance—it generates a makefile for the application depending on the selected switches and performs a long list of requirement checks on your system. Once the configure script is successfully executed, you can proceed with compiling Nginx.
Compiling the project equates to executing the make command in the project source directory:
[alex@example.com nginx-1.8.0]$ make
A successful build should result in the appearance of a final message: make[1]: leaving directory. This should be followed by the project source path.
Again, problems might occur at compile time. Most of these problems can originate in missing prerequisites or the specification of invalid paths. If this occurs, run the configure command again and triple-check the switches and all of the prerequisite options. It may also so happen that you downloaded an overly recent version of the prerequisites, which may not be backwards compatible. In such cases, the best option is to visit the official website of the missing component and download an older version.
If the compilation process was successful, you are ready for the next step: installing the application. The following command must be executed with root privileges:
[root@example.com nginx-1.8.0]# make install
The make install command executes the install section of the make file. In other words, it performs a few simple operations, such as copying binaries and configuration files to the specified install folder. It also creates directories to store log and HTML files if these do not already exist. The make install step is not generally a source of problems, unless your system encounters an exceptional error, such as a lack of storage space or memory.
Note
You may require root privileges to install the application in the /usr/local/ folder, depending on the folder permissions.
Controlling the Nginx service
At this stage, you should have successfully built and installed Nginx. The default location for the output files is /usr/local/nginx, so we will be basing future examples on this.
Nginx daemon into an actual system servic
Adding Nginx as a system service
#2Basic Nginx Configuration
In this chapter, we will establish an appropriate configuration for your web server. For this purpose, we begin to discover the syntax that is used in the Nginx configuration files.
Then, we need to understand the various directives that will let you prepare and optimize your web server for the different traffic patterns and hardware setups. Finally, we will create some test pages to make sure that everything has been done correctly and that the configuration is valid. We will only approach the basic configuration directives here. The following chapters will explore more advanced topics such as HTTP module configuration and usage, creating virtual hosts, and more.
This chapter covers the following topics:
The presentation of the configuration syntax An overview of basic configuration directives
Establishing an appropriate configuration for your profile Serving a test website
Testing and maintaining your web server
Configuration file syntax
A configuration file is generally a text file that is edited by the administrator and parsed by a program. By specifying a set of values, you define the behavior of the program. In
Linux-based operating systems, a large share of the applications rely on vast, complex configuration files, which often turn out to be a nightmare to manage. Apache, Qmail, and Bind—all these names bring up bad memories in the mind of a Linux system administrator. The fact is that all these applications use their own configuration file with different syntaxes and styles. PHP works with a Windows-style .ini file, sendmail uses the M4 macro-processor to compile the configuration files, Zabbix pulls its configuration from a MySQL database, and so on. There is, unfortunately, no well-established standard, and the same applies to Nginx—you will be required to study a new syntax with its own particularities and its own vocabulary.
Why isn’t there a universal standard for configuration file syntax? A possible explanation by Randall Munroe (xkcd.com – reproduced with authorization)
On the other hand (and this is one of its advantages), configuring Nginx turns out to be rather simple—at least in comparison to Apache or other mainstream web servers. There are only a few mechanisms that need to be mastered—directives, blocks, and the overall logical structure. Most of the actual configuration process will consist of writing values for the directives.
Configuration directives
The Nginx configuration file can be described as a list of directives organized in a logical structure. The entire behavior of the application is defined by the values that you give to those directives.
By default, Nginx makes use of one main configuration file. The path of this file was defined in the steps described in Chapter 1, Downloading and Installing Nginx, under the Build configuration section. If you did not edit the configuration file path and prefix options, it should be located at /usr/local/nginx/conf/nginx.conf. However, if you installed Nginx with a package manager, your configuration file will likely be located in the /etc/nginx folder, and the contents of the file may be quite different from the version that comes in the original Nginx source code package. Now, let’s take a quick peek at the first few lines of this initial setup:
The default configuration file bundled with the Nginx 1.8.0 source code package
Let’s take a closer look at the first two lines:
#user nobody; worker_processes 1;
As you can probably make out from the # character, the first line is a comment. In other words, a piece of text that is not interpreted and has no value whatsoever. Its sole purpose is to be read by whoever opens the file, or to temporarily disable parts of an existing configuration section. You may use the # character at the beginning of a line or following a directive.
The second line is an actual statement—a directive. The first bit (worker_processes) represents a setting key to which you append one or more values. In this case, the value is 1, indicating that Nginx should function with a single worker process (more information about this particular directive is given in later sections).
Note
Directives always end with a semicolon (;).
Each directive has a unique meaning and defines a particular feature of the application. It may also have a particular syntax. For example, the worker_process directive only accepts one numeric value, whereas the user directive lets you specify up to two character strings—one for the user account (that the Nginx worker processes should run as) and a second for the user group.
Nginx works in a modular way, and as such, each module comes with a specific set of directives. The most fundamental directives are part of the Nginx Core module and will be detailed in this chapter. As for the directives brought in by other modules, they will be explored in the later chapters.
Organization and inclusions
In the preceding screenshot, you may have noticed a particular directive—include.
include mime.types;
As the name suggests, this directive will perform an inclusion of the specified file. In other words, the contents of the file will be inserted at this exact location. Here is a practical example that will help you understand this concept:
nginx.conf:
user nginx nginx; worker_processes 4;
include other_settings.conf; other_settings.conf:
error_log logs/error.log; pid logs/nginx.pid;
The final result, as interpreted by Nginx, is as follows:
user nginx nginx; worker_processes 4; error_log logs/error.log; pid logs/nginx.pid;
Inclusions are processed recursively. In this case, you have the possibility to use the include directive again in the other_settings.conf file in order to include yet another file.
In the initial configuration setup, there are two files in use—nginx.conf and mime.types. However, in the case of a more advanced configuration, there may be five or more files, as described in the following table:
Standard name |
Description |
nginx.conf |
Base configuration of the application. |
mime.types |
A list of file extensions and their associated MIME types. |
fastcgi_params |
Fast CGI-related configuration. |
proxy.conf |
Proxy-related configuration. |
sites.conf |
Configuration of the websites served by Nginx, also known as virtual hosts. It’s recommended to create separate files for each domain. |
These filenames were defined conventionally; nothing actually prevents you from regrouping your FastCGI and proxy settings into a common file named proxy_and_fastcgi_config.conf.
Note that the include directive supports filename globbing, that is, filenames referenced
with the * wildcard, where * may match zero, one, or more consecutive characters:
include sites/*.conf;
This will include all the files with a name that ends with .conf in the sites folder. This mechanism allows you to create a separate file for each of your websites and include them all at once.
Be careful when including a file—if the specified file does not exist, the configuration checks will fail, and Nginx will not start:
[alex@example sbin]# ./nginx -t
[emerg]: open() “/usr/local/nginx/conf/dummyfile.conf” failed (2: No such file or directory) in /usr/local/nginx/conf/nginx.conf:48
The previous statement is not true for the inclusions with wildcards. If you insert include dummy*.conf in your configuration file and test it (whether there is any file matching this pattern on your system or not), the following is what should happen:
[alex@example sbin]# ./nginx –t
the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok configuration file /usr/local/nginx/conf/nginx.conf test is successful
Directive blocks
Directives are brought in by modules—if you activate a new module, a specific set of directives becomes available. Modules may also enable directive blocks, which allow for a logical construction of the configuration:
events {
worker_connections 1024;
}
The events block that you can find in the default configuration file is brought in by the
Events module. The directives that the module enables can only be used within that block
—in the preceding example, worker_connections will only make sense in the context of the events block. On the other hand, some directives must be placed at the root of the configuration file, because they have a global effect on the server. The root of the configuration file is also known as the main block.
For the most part, blocks can be nested into each other, following a specific logic. The following sequence demonstrates the structure of a simple website setup, making use of nested blocks:
http {
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.log; location ^~ /admin/ {
index index.php;
}
}
}
The topmost directive block is the http block, in which you may declare a variety of configuration directives as well as one or more server blocks. A server block allows you to configure a virtual host, in other words, a website that is to be hosted on your machine. The server block, in this example, contains some configuration that applies to all HTTP requests with a Host header exactly matching example.com.
Within this server block, you may insert one or more location blocks. These allow you to enable settings only when the requested URI matches the specified path. More information is provided in the The Location block section of Chapter 3, HTTP Configuration.
Last but not least, configuration is inherited within children blocks. The access_log directive (defined at the server block level in this example) specifies that all HTTP requests for this server should be logged into a text file. This is still true within the location child block, although you have the option of disabling it by reusing the access_log directive:
[…]
location ^~ /admin/ {
}
[…]
index index.php; access_log off;
In this case, logging will be enabled everywhere on the website except for the /admin/ location path. The value set for the access_log directive at the server block level is overridden by the one at the location block level.
Advanced language rules
There are a number of important observations regarding the Nginx configuration file syntax. These will help you understand certain language rules that may seem confusing if you have never worked with Nginx before.
Directives accept specific syntaxes
You may indeed stumble upon complex syntaxes that can be confusing at first sight, like the following one:
rewrite ^/(.*)\.(png|jpg|gif)$ /image.php? file=$1&format=$2 last;
Syntaxes are directive-specific. While the root directive only accepts a simple character string defining the folder containing the files that should be served for a website, the location block and the rewrite directive support complex expressions in order to match particular patterns. Some other directives such as listen accept up to 17 different parameters. Syntaxes will be explained along with directives in their respective chapters.
Later on, we will detail a module (the Rewrite module) which allows for a much more advanced logical structure through the if, set, break, and return blocks and directives, and the use of variables. With all these new elements, configuration files will begin to look like programming scripts. You will find that, the more modules we discover, the richer the syntax becomes.
Diminutives in directive values
Finally, you may use the following diminutives for specifying a file size in the context of a directive value:
k or K: Kilobytes m or M: Megabytes g or G: Gigabytes
As a result, the following three syntaxes are correct and equal:
client_max_body_size 2G; client_max_body_size 2048M; client_max_body_size 2097152k;
Note that Nginx does not allow you to insert the same directive more than once within the same block (although there are a few exceptions, such as allow or deny); should you do so, the configuration will be considered invalid, and Nginx will refuse to start up or reload.
Additionally, when specifying a time value, you may use the following shortcuts: ms: Milliseconds
s: Seconds
m: Minutes h: Hours
d: Days
w: Weeks
M: Months (30 days) y: Years (365 days)
This becomes especially useful in the case of directives accepting a period of time as a value:
client_body_timeout 3m; client_body_timeout 180s; client_body_timeout 180;
Note that the default time unit is seconds; the last two lines in the preceding list thus result in an identical behavior. It is also possible to combine two values with different units:
client_body_timeout 1m30s; client_body_timeout ‘1m 30s 500ms’;
The latter variant is enclosed in quotes since values are separated by spaces.
Variables
Modules also provide variables that can be used in the definition of directive values. For example, the Nginx HTTP core module defines the $nginx_version variable. Variables in Nginx always start with $—the dollar sign. When setting the log_format directive, you may include all kinds of variables in the format string:
[…]
location ^~ /admin/ { access_log logs/main.log;
log_format main ‘$pid – $nginx_version – $remote_addr’;
}
[…]
Note that some directives do not allow you to use variables:
error_log logs/error-$nginx_version.log;
The preceding directive is valid, syntax-wise. However, it simply generates a file named
error-$nginx_version.log without parsing the variable.
String values
Character strings that you use as directive values can be written in three forms. First, you may enter the value without quotes:
root /home/example.com/www;
However, if you want to use a particular character, such as a blank space (” “), a semicolon (;), or curly braces ({ and }), you will need to either prefix the said character with a backslash (\), or enclose the entire value in single or double quotes:
root ‘/home/example.com/my web pages’;
In Nginx, it makes no difference whether you use single or double quotes. Note that the variables inserted in strings within quotes will be expanded normally, unless you prefix
the $ character with a backslash (\).
Base module directives
In this section, we will take a closer look at the base modules. We are particularly interested in answering two questions: what are base modules? What are the directives that are available?
What are base modules?
The base modules offer directives that allow you to define the parameters of the basic functionality of Nginx. They cannot be disabled at compile time, and as a result, the directives and blocks that they offer are always available. Three base modules have been distinguished:
Core module: Consists of essential features and directives such as process management and security
Events module: Lets you configure the inner mechanisms of the networking capabilities
Configuration module: Enables the inclusion mechanism
These modules offer a large range of directives; we will be detailing them individually with their syntaxes and default values.
The Nginx process architecture
Before we start detailing the basic configuration directives, it is necessary to understand the overall process architecture, that is, the way that the Nginx daemon works behind the scenes. Although the application comes as a simple binary file (and a somewhat lightweight background process), the way it functions at runtime can be relatively complex.
A unique process—the Master Process—exists in memory from the very moment that Nginx starts. It is launched with the current user and group permissions—usually root/root if the service is launched at boot time by an init script. The master process itself does not process any client request; instead, it spawns the processes that do, that is, the Worker Processes, which are affected to a customizable user and group.
From the configuration file, you can define the number of worker processes, the maximum connections per worker process, the user and group that the worker processes are running under, and more. The following screenshot shows an example of a running instance of Nginx with eight worker processes running under the www-data user account.
Core module directives
The following is the list of directives made available by the core module. Most of these directives must be placed at the root of the configuration file, and can only be used once. However, some of them are valid in multiple contexts. If that is the case, the following is the list of valid contexts under the directive name:
Name and context |
Syntax and description |
daemon |
Accepted values: on or off Syntax: daemon on; Default value: on Enables or disables daemon mode. If you disable it, the program will not be started in the background; it will stay in the foreground when launched from the shell. This may come in handy for debugging, in situations where you need to know what causes Nginx to crash and when. |
debug_points |
Accepted values: stop or abort Syntax: debug_points stop; Default value: None Activates debug points in Nginx. Use stop to interrupt the application when a debug point comes about in order to attach a debugger. Use abort to abort the debug point and create a core dump file. To disable this feature, simply do not use the directive. |
env |
Syntax: env MY_VARIABLE; env MY_VARIABLE=my_value; Allows you to define or redefine environment variables. |
error_log Context: main, http, server, and location |
Syntax: error_log /file/path level; Default value: logs/error.log error. Where level is one of the following values: debug, info, notice, warn, error, crit, alert, emerg (from the most to least detailed: debug provides frequent log entries, emerg reports only the most critical errors). Enables error logging at different levels: Application, HTTP server, virtual host, and virtual host directory. By redirecting the log output to /dev/null, you can disable error logging. Use the following directive at the root of the configuration file: error_log /dev/null crit; Instead of specifying a file path, you might also select one of the following alternatives: stderr will send log entries to the standard error file, syslog to the system log, and memory will store the log entries in the memory. |
Syntax: File path |
lock_file |
lock_file logs/nginx.lock; Default value: Defined at compile time Use a lock file for mutual exclusion. This is disabled by default, unless you enabled it at compile time. On most operating systems, locks are implemented using atomic operations, so this directive is ignored anyway. |
log_not_found Context: main, http, server, and location |
Accepted values: on or off log_not_found on; Default value: on Enables or disables the logging of 404 not found HTTP errors. If your logs get filled with 404 errors due to missing favicon.ico or robots.txt files, you might want to turn this off. |
master_process |
Accepted values: on or off master_process on; Default value: on If enabled, Nginx will start multiple processes: a main process (the master process) and worker processes. If disabled, Nginx works with a unique process. This directive should be used for testing purposes only, as it disables the master process—thus, clients will not be able to connect to your server. |
pcre_jit |
Accepted values: on or off pcre_jit on; Enables or disables the Just-In-Time compilation for regular expressions (PCRE from version 8.20 and above), which may speed up their processing significantly. For this to work, the PCRE libraries on your system must be specifically built with the –enable-jit configuration argument. When configuring your Nginx build, you must also add the –with- pcre-jit argument. |
pid |
Syntax: File path pid logs/nginx.pid; Default value: Defined at compile time. Path of the pid file for the Nginx daemon. The default value can be configured at compile time. Make sure to enable this directive, and set its value properly, since the pid file may be used by the Nginx init script depending on your operating system. |
ssl_engine |
Syntax: Character string ssl_engine enginename; Default value: None Where enginename is the name of an available hardware SSL accelerator on your system. To check for the available hardware SSL accelerators, run this command from the shell: openssl engine –t |
thread_pool |
Syntax: thread_pool name threads=number [max_queue=number]; Default value: thread_pool default threads=32 max_queue=65536; Defines a thread pool reference that can be used with the aio directive for serving larger files asynchronously. Further details are provided in Chapter 8, Introducing Load Balancing and |
Optimization. |
|
timer_resolution |
Syntax: Numeric (time) timer_resolution 100ms; Default value: None Controls the interval between system calls to gettimeofday() for synchronizing the internal clock. If this value is not specified, the clock is refreshed after each kernel event notification. |
user |
Syntax: user username groupname; user username; Default value: Defined at compile time. If still undefined, the user and the group of the Nginx master process are used. Allows you to define the user account, and optionally, the user group used for starting the Nginx worker processes. For security reasons, you should make sure to specify a user and a group with limited privileges. For example, create a new user and a group dedicated to Nginx, and remember to apply proper permissions on the files that will be served. |
worker_cpu_affinity |
Syntax: worker_cpu_affinity 1000 0100 0010 0001; worker_cpu_affinity 10 10 01 01; worker_cpu_affinity; Default value: None This directive works in conjunction with worker_processes. It lets you affect the worker processes to CPU cores. There are as many series of digit blocks as worker processes; there are as many digits in a block as your CPU has cores. If you configure Nginx to use three worker processes, there are three blocks of digits. For a dual-core CPU, each block has two digits: worker_cpu_affinity 01 01 10; The first block (01) indicates that the first worker process should be affected to the second core. The second block (01) indicates that the second worker process should be affected to the second core. The third block (10) indicates that the third worker process should be affected to the first core. Note that affinity is only recommended for multi-core CPUs, not for processors with hyper- treading or similar technologies. |
worker_priority |
Syntax: Numeric worker_priority 0; Default value: 0 Defines the priority of the worker processes, from -20 (highest) to 19 (lowest). The default value is 0. Note that the kernel processes run at priority level -5, so it’s not recommended that you set the priority to -5 or less. |
Syntax: Numeric or auto worker_processes 4; Default value: 1 |
worker_processes |
Defines the number of worker processes. Nginx offers to separate the treatment of requests into multiple processes. The default value is 1, but it’s recommended to increase this value if your CPU has more than one core. Besides, if a process gets blocked due to slow I/O operations, the incoming requests can be delegated to the other worker processes. Alternatively, you may use the auto value, which will let Nginx select an appropriate value for this directive. By default, it is the amount of CPU cores detected on the system. |
worker_rlimit_core |
Syntax: Numeric (size) worker_rlimit_core 100m; Default value: None Defines the size of core files per worker process. |
worker_rlimit_nofile |
Syntax: Numeric worker_rlimit_nofile 10000; Default value: None Defines the number of files that a worker process may use simultaneously. |
working_directory |
Syntax: Directory path working_directory /usr/local/nginx/; Default value: The prefix switch defined at compile time. A working directory used for worker processes, it is only used to define the location of the core files. The worker process user account (user directive) must have write permissions on this folder in order to be able to write core files. |
worker_aio_requests |
Syntax: Numeric worker_aio_requests 10000; If you are using aio with the epoll connection processing method, this directive sets the maximum number of outstanding asynchronous I/O operations for a single worker process. |
The Events module
The Events module comes with directives that allow you to configure the network mechanisms. Some of the parameters have an important impact on the application’s performance.
All the directives listed in the following table must be placed in the events block, which is located at the root of the configuration file:
user nginx nginx; master_process on; worker_processes 4; events {
worker_connections 1024; use epoll;
} […]
These directives cannot be placed elsewhere (if you do so, the configuration test will fail).
Directive name |
Syntax and description |
accept_mutex |
Accepted values: on or off accept_mutex on; Default value: on Enables or disables the use of an accept mutex (mutual exclusion) to open the listening sockets. |
accept_mutex_delay |
Syntax: Numeric (time) accept_mutex_delay 500ms; Default value: 500 milliseconds Defines the amount of time that a worker process should wait for before trying to acquire the resource again. This value is not used if the accept_mutex directive is set to off. |
debug_connection |
Syntax: IP address or CIDR block. debug_connection 172.63.155.21; debug_connection 172.63.155.0/24; Default value: None Writes detailed logs for clients matching this IP address or address block. The debug information is stored in the file specified with the error_log directive, enabled with the debug level. Note: Nginx must be compiled with the –debug switch in order to enable this feature. |
multi_accept |
Syntax: on or off multi_accept off; Default value: off Defines whether or not Nginx should accept all the incoming connections at once from the listening queue. |
Accepted values: /dev/poll, epoll, eventport, kqueue, rtsig, or select |
use |
use kqueue; Default value: Defined at compile time Selects the event model among the available ones (the ones that you enabled at compile time). Nginx automatically selects the most appropriate one, so you should not have to modify this value. The supported models are: select: The default and standard module, it is used if the OS does not support a more efficient one (it’s the only available method under Windows). This method is not recommended for servers that expect to be under high load. poll: It is automatically preferred over select, but is not available on all systems. kqueue: An efficient method for the FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0, and MacOS X operating systems. epoll: An efficient method for Linux 2.6+ based operating systems. rtsig: Real-time signals, available as of Linux 2.2.19, but unsuited for high-traffic profiles, as the default system settings allow only 1,024 queued signals. /dev/poll: An efficient method for the Solaris 7 11/99+, HP/UX 11.22+, IRIX 6.5.15+, and Tru64 UNIX 5.1A+ operating systems. eventport: An efficient method for Solaris 10, though a security patch is required. |
worker_connections |
Syntax: Numeric worker_connections 1024; Default value: None Defines the number of connections that a worker process may treat simultaneously. |
The Configuration module
The Nginx Configuration module is a simple module enabling file inclusions with the include directive, as previously described in the Organization and inclusions section. The directive can be inserted anywhere in the configuration file and accepts a single parameter
—a file path.
include /file/path.conf; include sites/*.conf;
Note
Note that if you do not specify an absolute path, the file path is relative to the configuration directory. By default, include sites/example.conf will include the following file: /usr/local/nginx/conf/sites/example.conf
Necessary adjustments
Several core directives deserve to be adjusted carefully upon preparing the initial setup of Nginx on your server. We will review several of these directives and the possible values that you may set:
user root root;
This directive specifies that the worker processes is started as root. This is dangerous from the security point of view, as it grants Nginx full permissions over your file system. You need to create a new user account on your system and make use of it there.
Recommended value (granted that a www-data user account and group exist on the system): user www-data www-data;
worker_processes 1;
With this setting, only one worker process is started, which implies that all the requests will be processed by a unique execution flow. This also implies that the execution is delegated to only one core of your CPU. It is highly recommended to increase this value; you should have at least one process per CPU core. Alternatively, just set this to auto to leave it up to Nginx to determine the optimal value.
Recommended value: worker_processes auto; worker_priority 0;
By default, the worker processes are started with a regular priority. If your system
performs other tasks simultaneously, you might want to grant a higher priority to the Nginx worker processes. In this case, you should decrease the value—the smaller the value, the higher the priority. Values range from -20 (highest priority) to 19 (lowest priority). There is no recommended value here, as it completely depends on your situation. However, you should not set it under -5, as it is the default priority for kernel processes.
log_not_found on;
This directive specifies whether Nginx should log 404 errors or not. While these errors may, of course, provide useful information about the missing resources, a lot of them may be generated by web browsers trying to reach the favicon (the conventional
/favicon.ico of a website), or robots trying to access the indexing instructions (robots.txt). Set this to off if you want to ensure that your log files don’t get cluttered by Error 404 entries, but keep in mind that this could deprive you from potentially important information about other pages that visitors failed to reach. Note that this directive is part of the HTTP core module. Refer to the next chapter for more information.
worker_connections 1024;
This setting, combined with the number of worker processes, allows you to define the total number of connections accepted by the server simultaneously. If you enable four
worker processes, each accepting 1,024 connections, your server will treat a total of 4,096 simultaneous connections. You need to adjust this setting to match your hardware: the more RAM and CPU power your server relies on, the more connections you can accept concurrently. If your server is a huge monster meant to host high traffic sites, you will want to increase this value.
Upgrading Nginx gracefully on production serer
There are many situations where you need to replace the Nginx binary, for example, when you compile a new version and wish to put it in production, or simply after having enabled new modules and rebuilt the application. What most administrators would do in this situation is stop the server, copy the new binary over the old one, and start Nginx again.
While this is not considered to be a problem for most websites, there may be some cases where the uptime is critical, and connection losses should be avoided at all costs.
Fortunately, Nginx embeds a mechanism allowing you to switch binaries with uninterrupted uptime—zero percent request loss is guaranteed if you follow these steps carefully:
- Replace the old Nginx binary (by default, /usr/local/nginx/sbin/nginx) with the new one.
- Find the pid of the Nginx master process, for example, with ps x | grep nginx | grep master, or by looking at the value found in the pid file.
- Send a USR2 (12) signal to the master process—kill –USR2 1234, replacing 1234 with the pid found in step 2. This will initiate the upgrade by renaming the old .pid file and running the new binary.
- Send a WINCH (28) signal to the old master process—kill –WINCH 1234, replacing 1234 with the pid found in step 2. This will engage a graceful shutdown of the old worker processes.
- Make sure that all the old worker processes are terminated, and then send a QUIT signal to the old master process—kill –QUIT 1234, replacing 1234 with the pid found in step 2.
Congratulations! You have successfully upgraded Nginx and have not lost a single connection.
Chapter 3. HTTP Configuration
At this stage, we have a working Nginx setup. Not only is it installed on the system and launched automatically on startup, but it’s also organized and optimized with the help of basic directives. It’s now time to go one step further into the configuration and discover the HTTP Core module. This module constitutes the essential component of the HTTP configuration—it allows you to set up websites to be served, also referred to as virtual hosts.
This chapter will cover the following topics:
An introduction to the HTTP Core module The http / server / location structure
HTTP Core module directives, organized thematically HTTP Core module variables
The in-depths of the location block
The HTTP Core module
three main blocks—http, server, and location.
Structure blocks
In the previous chapter, we discovered the Core module by studying the default Nginx configuration file, which includes a sequence of directives and values with no apparent organization. Then came the Events module, which introduced the first block (events). This block would be the only placeholder for all of the directives brought in by the Events module.
As it turns out, the HTTP module introduces three new logical blocks:
http: This block is inserted at the root of the configuration file. It allows you to start defining the directives and blocks from all the modules related to the HTTP facet of Nginx. Although there is no real purpose in doing so, the block can be inserted multiple times, in which case the directive values inserted in the last block will override the previous ones.
server: This block allows you to declare a website. In other words, a specific website (identified by one or more hostnames, for example, www.mywebsite.com) becomes acknowledged by Nginx and receives its own configuration. This block can only be used within the http block.
location: The location block lets you define a group of settings to be applied to a particular location on a website. This block can be used within a server block or nested within another location block.
The following diagram summarizes the final structure by providing a couple of basic examples corresponding to actual situations:
The HTTP section, defined by the http block, encompasses the entire web-related configuration. It may contain one or more server blocks, defining the domains and sub- domains that you are hosting. For each of these websites, you have the possibility of
defining location blocks that let you apply additional settings to a particular request URI or request URIs matching a pattern.
Remember that the principle of setting inheritance applies here. If you define a setting at the http block level (for example, gzip on to enable gzip compression), the setting preserves its value in the potentially incorporated server and location blocks:
http {
# Enable gzip compression at the http block level gzip on;
server {
server_name localhost; listen 80;
# At this stage, gzip still set to on
location /downloads/ { gzip off;
# This directive only applies to documents found # in /downloads/
}
}
}
Socket and host configuration
This set of directives allows you to configure your virtual hosts. In practice, this materializes by creating server blocks that you identify either by a hostname or by an IP address and port combination. In addition, some directives let you fine-tune your network settings by configuring the TCP socket options.
listen
Context: server
Specifies the IP address and/or the port to be used by the listening socket that serves the website. Sites are generally served on port 80 (the default value) via HTTP, or 443 via HTTPS.
Syntax: listen [address][:port] [additional options];
Additional options:
default_server: Specifies this server block to be used as the default website for any request received at the specified IP address and port
ssl: Specifies that the website should be served over SSL
spdy: Enables support for the SPDY protocol if the SPDY module is present proxy_protocol: Enables the PROXY protocol for all the connections accepted on this port
Other options are related to the bind and listen system calls: backlog=num, rcvbuf=size, sndbuf=size, accept_filter=filter, deferred, setfib=number, and
bind
Examples:
listen 192.168.1.1:80;
listen 127.0.0.1;
listen 80 default;
listen [:::a8c9:1234]:80; # IPv6 addresses must be put between square brackets
listen 443 ssl;
This directive also allows Unix sockets:
listen unix:/tmp/nginx.sock;
server_name
Context: server
This assigns one or more hostnames to the server block. When Nginx receives an HTTP request, it matches the Host header of the request against all the server blocks. The first server block to match this hostname is selected.
Plan B: if no server block matches the desired host, Nginx selects the first server block that matches the parameters of the listen directive (such as listen *:80 would be a catch-all for all the requests received on port 80), giving priority to the first block that has
the default option enabled on the listen directive.
Note that this directive accepts wildcards as well as regular expressions (in which case, the hostname should start with the ~ character).
Syntax: server_name hostname1 [hostname2…];
Examples:
server_name www.website.com; server_name www.website.com website.com; server_name *.website.com;
server_name .website.com; # combines both *.website.com and website.com server_name *.website.*;
server_name ~^(www)\.example\.com$; # $1 = www
Note that you may use an empty string as the directive value in order to catch all the requests that do not come with a Host header, but only after at least one regular name (or “_” for a dummy hostname):
server_name website.com “”; server_name _ “”;
server_name_in_redirect
Context: http, server, location
This directive applies to the case of internal redirects (for more information about internal redirects, check the Rewrite Module section given further on in this chapter). If set to on, Nginx uses the first hostname specified in the server_name directive. If set to off, Nginx uses the value of the Host header from the HTTP request.
Syntax: on or off
Default value: off server_names_hash_max_size Context: http
Nginx uses hash tables for various data collections in order to speed up the processing of requests. This directive defines the maximum size of the server names hash table. The default value fits with most configurations. If this needs to be changed, Nginx automatically tells you so on startup, or when you reload its configuration.
Syntax: Numeric value Default value: 512
server_names_hash_bucket_size
Context: http
Sets the bucket size for server names hash tables. You should only change this value if Nginx tells you to.
Syntax: Numeric value
Default value: 32 (or 64, or 128, depending on your processor cache specifications)
port_in_redirect
Context: http, server, location
In case of a redirect, this directive defines whether or not Nginx should append the port number to the redirection URL.
Syntax: on or off Default value: on tcp_nodelay
Context: http, server, location
Enables or disables the TCP_NODELAY socket option for keep-alive connections only. Quoting the Linux documentation on sockets programming:
“TCP_NODELAY is for a specific purpose; to disable the Nagle buffering algorithm. It should only be set for applications that send frequent small bursts of information without getting an immediate response, where timely delivery of data is required (the canonical example is mouse movements).”
Syntax: on or off Default value: on tcp_nopush
Context: http, server, location
Enables or disables the TCP_NOPUSH (FreeBSD) or TCP_CORK (Linux) socket option. Note that this option applies only if the sendfile directive is enabled. If tcp_nopush is set to on, Nginx attempts to transmit all the HTTP response headers in a single TCP packet.
Syntax: on or off Default value: off sendfile
Context: http, server, location
If this directive is enabled, Nginx uses the sendfile kernel call to handle file transmission. If disabled, Nginx handles the file transfer by itself. Depending on the physical location of the file being transmitted (such as NFS), this option may affect the server performance.
Syntax: on or off Default value: off sendfile_max_chunk
Context: http, server
This directive defines the maximum size of data to be used for each call to sendfile (read the previous section).
Syntax: Numeric value (size) Default value: 0 send_lowat
Context: http, server
This is an option that allows you to make use of the SO_SNDLOWAT flag for TCP sockets under FreeBSD only. This value defines the minimum number of bytes in the buffer for output operations.
Syntax: Numeric value (size) Default value: 0 reset_timedout_connection Context: http, server, location
When a client connection times out, its associated information may remain in memory depending on its state. Enabling this directive will erase all memory associated with the connection after it times out.
Syntax: on or off
Default value: off
Paths and documents
This section describes the directives that configure the documents that should be served for each website, such as the document root, the site index, error pages, and so on.
root
Context: http, server, location, if. Variables are accepted.
This directive defines the document root containing the files that you wish to serve to your visitors.
Syntax: Directory path Default value: html
root /home/website.com/public_html;
alias
Context: location. Variables are accepted.
alias is a directive that you place in a location block only. It assigns a different path for Nginx to retrieve documents for a specific request. As an example, consider the following configuration:
http {
server {
server_name localhost;
root /var/www/website.com/html; location /admin/ {
alias /var/www/locked/;
}
}
}
When a request for http://localhost/ is received, files are served from the
/var/www/website.com/html/ folder. However, if Nginx receives a request for http://localhost/admin/, the path used to retrieve the files is var/www/locked/. Moreover, the value of the document root directive (root) is not altered. This procedure is invisible in the eyes of dynamic scripts.
Syntax: Directory (do not forget the trailing /) or file path
error_page
Context: http, server, location, if. Variables are accepted.
This allows you to affect URIs to the HTTP response code and optionally, to substitute the code with another.
Syntax: error_page code1 [code2…] [=replacement code] [=@block | URI]
Examples :
error_page 404 /not_found.html;
error_page |
500 |
501 502 503 504 /server_error.html; |
error_page |
403 |
http://website.com/; |
error_page |
404 |
@notfound; # jump to a named location block |
error_page |
404 |
=200 /index.html; # in case of 404 error, redirect to |
index.html with a 200 OK response code
if_modified_since
Context: http, server, location
This defines the way Nginx handles the If-Modified-Since HTTP header. This header is mostly used by search engine spiders (such as Google web crawling bots). The robot indicates the date and time of the last pass. If the requested file has not been modified since that time, the server simply returns a 304 Not Modified response code with no body.
This directive accepts the following three values:
off: Ignores the If-Modified-Since header.
exact: Returns 304 Not Modified if the date and time specified in the HTTP header are an exact match with the actual requested file modification date. If the file modification date is anterior or ulterior, the file is served normally (200 OK response). before: Returns 304 Not Modified if the date and time specified in the HTTP header is anterior or equal to the requested file modification date.
Syntax: if_modified_since off | exact | before
Default value: exact
index
Context: http, server, location. Variables are accepted.
This defines the default page that Nginx will serve if no filename is specified in the request (in other words, the index page). You may specify multiple filenames, and the first file to be found will be served. If none of the specified files are found, and if the autoindex directive is enabled (check the HTTP Autoindex module), Nginx will attempt to generate an automatic index of the files. Otherwise, it will return a 403 Forbidden error page. Optionally, you may insert an absolute filename (such as /page.html, based from the document root directory) but only as the last argument of the directive.
Syntax: index file1 [file2…] [absolute_file];
Default value: index.html
index index.php index.html index.htm; index index.php index2.php /catchall.php;
recursive_error_pages
Context: http, server, location
Sometimes, an error page itself served by the error_page directive may trigger an error; in this case, the error_page directive is used again (recursively). This directive enables or
disables recursive error pages. Syntax: on or off
Default value: off
try_files
Context: server, location. Variables are accepted.
This attempts to serve the specified files (arguments 1 to N-1). If none of these files exist, it jumps to the respective named location block (last argument) or serves the specified URI.
Syntax: Multiple file paths followed by a named location block or a URI Example:
location / {
try_files $uri $uri.html $uri.php $uri.xml @proxy;
}
# the following is a “named location block” location @proxy {
proxy_pass 127.0.0.1:8080;
}
In this example, Nginx tries to serve files normally. If the requested URI does not correspond to any existing file, Nginx appends .html to the URI and tries to serve the file again. If it fails again, it tries with .php, and then with .xml. Eventually, if all of these possibilities fail, another location block (@proxy) handles the request.
Note
You may also specify $uri/ in the list of values in order to test for the existence of a directory with that name.
Client requests
This section documents the way that Nginx handles client requests. Among other things, you are allowed to configure the keep-alive mechanism behavior and, possibly, logging the client requests into files.
keepalive_requests
Context: http, server, location
This specifies the maximum number of requests served over a single keep-alive connection.
Syntax: Numeric value Default value: 100 keepalive_timeout
Context: http, server, location
This directive defines the number of seconds the server will wait before closing a keep- alive connection. The second (optional) parameter is transmitted as the value of the Keep- Alive: timeout= HTTP response header. The intended effect is to let the client browser close the connection itself after this period has elapsed. Note that some browsers ignore this setting. Internet Explorer, for instance, automatically closes the connection after around 60 seconds.
Syntax: keepalive_timeout time1 [time2];
Default value: 75
keepalive_timeout 75;
keepalive_timeout 75 60;
keepalive_disable
Context: http, server, location
This option allows you to disable the keepalive functionality for the browser families of your choice.
Syntax: keepalive_disable browser1 browser2;
Default value: msie6
send_timeout
Context: http, server, location
This specifies the amount of time after which Nginx closes an inactive connection. A connection becomes inactive the moment a client stops transmitting data.
Syntax: Time value (in seconds) Default value: 60
client_body_in_file_only
Context: http, server, location
If this directive is enabled, the body of the incoming HTTP requests will be stored into actual files on the disk. The client body corresponds to the client HTTP request raw data, minus the headers (in other words, the content transmitted in POST requests). Files are stored as plain text documents.
This directive accepts three values:
off: Does not store the request body in a file
clean: Stores the request body in a file, and removes the file after a request is processed
on: Stores the request body in a file, but does not remove the file after the request is processed (not recommended unless for debugging purposes)
Syntax: client_body_in_file_only on | clean | off
Default value: off client_body_in_single_buffer Context: http, server, location
This directive defines whether or not Nginx should store the request body in a single buffer in memory.
Syntax: on or off
Default value: off client_body_buffer_size Context: http, server, location
The client_body_buffer_size directive specifies the size of the buffer holding the body of client requests. If this size is exceeded, the body (or at least a part of it) will be written to the disk. Note that if the client_body_in_file_only directive is enabled, request bodies are always stored to a file on the disk, regardless of their size (whether they fit in the buffer or not).
Syntax: Size value
Default value: 8k or 16k (2 memory pages) depending on your computer architecture
client_body_temp_path
Context: http, server, location
This option allows you to define the path of the directory that will store the client request body files. An additional option lets you separate those files into a folder hierarchy of up to three levels.
Syntax: client_body_temp_path path [level1] [level2] [level3]
Default value: client_body_temp
client_body_temp_path /tmp/nginx_rbf;
client_body_temp_path temp 2; # Nginx will create 2-digit folders to hold request body files
client_body_temp_path temp 1 2 4; # Nginx will create 3 levels of folders (first level: 1 digit, second level: 2 digits, third level: 4 digits)
client_body_timeout
Context: http, server, location
This directive defines the inactivity timeout while reading a client request body. A connection becomes inactive the moment the client stops transmitting data. If the delay is reached, Nginx returns a 408 Request timeout HTTP error.
Syntax: Time value (in seconds) Default value: 60 client_header_buffer_size Context: http, server, location
This directive allows you to define the size of the buffer that Nginx allocates to request headers. Usually, 1k is enough. However, in some cases, the headers contain large chunks of cookie data or the request URI is lengthy. If that is the case, then Nginx allocates one or more larger buffers (the size of larger buffers is defined by the large_client_header_buffers directive).
Syntax: Size value Default value: 1k
client_header_timeout
Context: http, server, location
This defines the inactivity timeout while reading a client request header. A connection becomes inactive the moment the client stops transmitting data. If the delay is reached, Nginx returns a 408 Request timeout HTTP error.
Syntax: Time value (in seconds) Default value: 60 client_max_body_size Context: http, server, location
This is the maximum size of a client request body. If this size is exceeded, Nginx returns a
413 Request entity too large HTTP error. This setting is particularly important if you are going to allow users to upload files to your server over HTTP.
Syntax: Size value Default value: 1m
large_client_header_buffers
Context: http, server, location
This defines the amount and size of the larger buffers to be used for storing client requests in case the default buffer (client_header_buffer_size) is insufficient. Each line of the header must fit in the size of a single buffer. If the request URI line is greater than the size of a single buffer, Nginx returns the 414 Request URI too large error. If another header line exceeds the size of a single buffer, Nginx returns a 400 Bad request error.
Syntax: large_client_header_buffers amount size
Default value: 4*8 kilobytes
lingering_time
Context: http, server, location
This directive applies to the client requests with a request body. As soon as the amount of uploaded data exceeds max_client_body_size, Nginx immediately sends a 413 Request entity too large HTTP error response. However, most browsers continue uploading data regardless of that notification. This directive defines the amount of time Nginx should wait for after sending this error response before it closes the connection.
Syntax: Numeric value (time) Default value: 30 seconds lingering_timeout
Context: http, server, location
This directive defines the amount of time that Nginx should wait between two read operations before it closes the client connection.
Syntax: Numeric value (time) Default value: 5 seconds lingering_close
Context: http, server, location
The lingering_close directive controls the way Nginx closes client connections. Set this to off to immediately close connections after all the request data has been received. The default value (on) allows Nginx to wait and process additional data if necessary. If set to always, Nginx will always wait to close the connection. The amount of waiting time is defined by the lingering_timeout directive.
Syntax: on, off, or always Default value: on ignore_invalid_headers Context: http, server
If this directive is disabled, Nginx returns a 400 Bad Request HTTP error in case the request headers are malformed.
Syntax: on or off
Default value: on chunked_transfer_encoding Context: http, server, location
This directive enables or disables chunked transfer encoding for HTTP 1.1 requests. Syntax: on or off
Default value: on
max_ranges
Context: http, server, location
This directive defines the number of byte ranges that Nginx will accept to serve when a client requests partial content from a file. If you do not specify a value, there is no limit. If you set this to 0, the byte range functionality is disabled.
Syntax: Size value
MIME types
Nginx offers two particular directives that help you configure the MIME types: types and default_type, which defines the default MIME types for documents. This will affect the Content-Type HTTP header sent within responses. Read on.
types
Context: http, server, location
This directive allows you to establish correlations between the MIME types and file extensions. It’s actually a block accepting a particular syntax:
types {
mimetype1 extension1;
mimetype2 extension2 [extension3…]; […]
}
When Nginx serves a file, it checks the file extension in order to determine the MIME type. The MIME type is then sent as the value of the Content-Type HTTP header in the response. This header may affect the way in which browsers handle files. For example, if the MIME type of the file you are requesting is application/pdf, your browser may, for instance, attempt to render the file using a plugin associated to that MIME type instead of merely downloading it.
Nginx includes a basic set of MIME types as a standalone file (mime.types) to be included with the include directive:
include mime.types;
This file already covers the most important file extensions, so you will probably not need to edit it. If the extension of the served file is not found within the listed types, the default type is used, as defined by the default_type directive (read below).
Note that you may override the list of types by re-declaring the types block. A useful example would be to force all the files in a folder to be downloaded instead of being displayed:
http {
include mime.types; […]
location /downloads/ {
# removes all MIME types types { }
default_type application/octet-stream;
}
[…]
}
Note that some browsers ignore the MIME types and may still display files if their filename ends with a known extension such as .html or .txt.
Note
To control the way files are handled by your visitors’ browsers in a more certain and definitive manner, you should make use of the Content-Disposition HTTP header via the add_header directive—detailed in the HTTP Headers module (Chapter 4, Module Configuration).
The default values, if the mime.types file is not included, are:
types {
text/html html; image/gif gif; image/jpeg jpg;
}
default_type
Context: http, server, location
This defines the default MIME type. When Nginx serves a file, the file extension is matched against the known types declared within the types block in order to return the proper MIME type as the value of the Content-Type HTTP response header. If the extension doesn’t match any of the known MIME types, the value of the default_type directive is used.
Syntax: MIME type Default value: text/plain types_hash_max_size
Context: http, server, location
This defines the maximum size of an entry in the MIME types hash tables. Syntax: Numeric value.
Default value: 4k or 8k (1 line of CPU cache)
types_hash_bucket_size
Context: http, server, location
This directive sets the bucket size for the MIME types hash tables. You should only change this value if Nginx tells you to.
Syntax: Numeric value. Default value: 64
Limits and restrictions
This set of directives allow you to add restrictions to be applied when a client attempts to access a particular location or document on your server. Note that you will find additional directives for restricting access in the next chapter.
limit_except
Context: location
This directive allows you to prevent the use of all the HTTP methods except the ones that you explicitly allow. Within a location block, you may want to restrict the use of some HTTP methods, for instance by forbidding clients from sending POST requests. You need to define two elements—first, the methods that are not forbidden (the allowed methods; all others will be forbidden), and second, the audience that is affected by the restriction:
location /admin/ { limit_except GET {
allow 192.168.1.0/24; deny all;
}
}
The preceding example applies a restriction to the /admin/ location—all visitors are only allowed to use the GET method. Visitors that have a local IP address, as specified with the allow directive (detailed in the HTTP Access module), are not affected by this restriction. If a visitor uses a forbidden method, Nginx will return a 403 Forbidden HTTP error. Note that the GET method implies the HEAD method (if you allow GET, both GET and HEAD are allowed).
The syntax for this is as follows:
limit_except METHOD1 [METHOD2…] {
allow | deny | auth_basic | auth_basic_user_file | proxy_pass | perl;
}
limit_rate
Context: http, server, location, if
This directive allows you to limit the transfer rate of individual client connections. The rate is expressed in bytes per second:
limit_rate 500k;
This will limit the connection transfer rates to 500 kilobytes per second. If a client opens two connections, the client will be allowed 2 * 500 kilobytes.
Syntax: Size value Default value: No limit
limit_rate_after
Context: http, server, location, if
This defines the amount of data transferred before the limit_rate directive takes effect.
limit_rate 10m;
Nginx sends the first 10 megabytes at the maximum speed. Past this size, the transfer rate is limited by the value specified with the limit_rate directive (see preceding section).
Similarly to the limit_rate directive, this setting applies only to a single connection. Syntax: Size value
Default: None
satisfy
Context: location
The satisfy directive defines whether clients require all access conditions to be valid (satisfy all) or at least one (satisfy any).
location /admin/ {
allow 192.168.1.0/24; deny all;
auth_basic “Authentication required”; auth_basic_user_file conf/htpasswd;
}
In the preceding example, there are two conditions for clients to be able to access the resource:
Through the allow and deny directives (HTTP Access module), we only allow clients that have a local IP address; all other clients are denied access.
Through the auth_basic and auth_basic_user_file directives (HTTP Auth Basic module), we only allow clients that provide a valid username and password.
With satisfy all, the client must satisfy both the conditions in order to gain access to the resource. With satisfy any, if the client satisfies either condition, they are granted access.
Syntax: satisfy any | all Default value: all internal
Context: location
This directive specifies that the location block is internal. In other words, the specified resource cannot be accessed by external requests.
server {
[…]
server_name .website.com;
location /admin/ { internal;
}
}
With the preceding configuration, clients will not be able to browse http://website.com/admin/. Such requests will be met with 404 Not Found errors. The only way to access the resource is via internal redirects (check the Rewrite module section for more information on internal redirects).
File processing and caching
It’s important for your websites to be built upon solid foundations. File access and caching is a critical aspect of web serving. In this instance, Nginx lets you perform precise tweaking with the use of the following directives.
disable_symlinks
This directive allows you to control the way Nginx handles symbolic links when they are to be served. By default (the directive value is off), symbolic links are allowed and Nginx follows them. You may decide to disable the following symbolic links under different conditions by specifying one of these values:
on: If any part of the requested URI is a symbolic link, access to it is denied, and Nginx returns a 403 HTTP error page.
if_not_owner: Similar to the preceding value, but access is denied only if the link and the object it points to have different owners.
The optional parameter from= allows you to specify a part of the URL that will not be checked for symbolic links. For example, disable_symlinks on from=$document_root will tell Nginx to normally follow the symbolic links in the URI up to the $document_root folder. If a symbolic link is found in the URI parts after that, access to the requested file will be denied.
directio
Context: http, server, location
If this directive is enabled, files with a size greater than the specified value will be read with the Direct I/O system mechanism. This allows Nginx to read data from the storage device and place it directly in memory with no intermediary caching process involved.
Syntax: Size value, or off Default value: off directio_alignment
Context: http, server, location
This directive sets the byte alignment when using directio. Set this value to 4k if you use XFS under Linux.
Syntax: Size value Default value: 512 open_file_cache
Context: http, server, location
This directive allows you to enable the cache, which stores information about open files. It does not actually store the file contents but only information such as:
File descriptors (file size, modification time, and so on).
The existence of files and directories.
File errors, such as Permission denied, File not found, and so on. Note that this can be disabled with the open_file_cache_errors directive.
This directive accepts two arguments:
max=X, where X is the number of entries that the cache can store. If this number is reached, older entries will be deleted in order to leave room for newer entries. inactive=Y, where Y is the number of seconds that a cache entry should be stored. By default, Nginx will wait for 60 seconds before clearing a cache entry. If the cache entry is accessed, the timer is reset. If the cache entry is accessed more often than the value defined by open_file_cache_min_uses, the cache entry will not be cleared (until Nginx runs out of space and decides to clear out the older entries).
Syntax: open_file_cache max=X [inactive=Y] | off
Default value: off
Example:
open_file_cache max=5000 inactive=180;
open_file_cache_errors
Context: http, server, location
This directive enables or disables the caching of file errors with the open_file_cache
directive (read the preceding directive). Syntax: on or off
Default value: off open_file_cache_min_uses Context: http, server, location
By default, entries in the open_file_cache are cleared after a period of inactivity (60 seconds, by default). However, if there is any activity, you can prevent Nginx from removing the cache entry. This directive defines the number of times an entry must be accessed in order to be eligible for protection.
open_file_cache_min_uses 3;
If the cache entry is accessed more than three times, it becomes permanently active and is not removed until Nginx decides to clear out the older entries to clear some space.
Syntax: Numeric value Default value: 1 open_file_cache_valid
Context: http, server, location
The open file cache mechanism is important, but the cached information quickly becomes
obsolete, especially in the case of a fast-moving filesystem. From that perspective, information needs to be re-verified after a short period of time. This directive specifies the number of seconds that Nginx will wait before revalidating a cache entry.
Syntax: Time value (in seconds) Default value: 60 read_ahead
Context: http, server, location
The read_ahead directive defines the number of bytes to be pre-read from the files. Under Linux-based operating systems, setting this directive to a value above 0 will enable reading ahead, but the actual value that you specify has no effect. Set this to 0 to disable pre-reading.
Syntax: Size value Default value: 0
Other directives
The following directives relate to various aspects of the web server—logging, URI composition, DNS, and so on.
log_not_found
Context: http, server, location
This directive enables or disables the logging of 404 Not Found HTTP errors. If your logs get filled with 404 errors due to missing favicon.ico or robots.txt files, you might want to turn this off.
Syntax: on or off Default value: on log_subrequest
Context: http, server, location
This directive enables or disables the logging of sub-requests triggered by internal redirects (see The Rewrite module section) or SSI requests (see the Server Side Includes module section).
Syntax: on or off Default value: off merge_slashes
Context: http, server, location
Enabling this directive will have the effect of merging multiple consecutive slashes in a URI. It turns out to be particularly useful in situations resembling the following:
server {
[…]
server_name website.com; location /documents/ {
type { }
default_type text/plain;
}
}
By default, if the client attempts to access http://website.com//documents/ (note the // in the middle of the URI), Nginx will return a 404 Not found HTTP error. If you enable this directive, the two slashes will be merged into one, and the location pattern will be matched.
Syntax: on or off Default value: off msie_padding
Context: http, server, location
This directive functions with the Microsoft Internet Explorer (MSIE) and Google Chrome browser families. In the case of error pages (with error code 400 or higher), if the length of the response body is less than 512 bytes, these browsers will display their own error page, sometimes at the expense of a more informative page provided by the server. If you enable this option, the body of responses with a status code of 400 or higher will be padded to 512 bytes.
Syntax: on or off Default value: off msie_refresh
Context: http, server, location
This is another MSIE-specific directive that takes effect in the case of HTTP response codes 301 Moved permanently and 302 Moved temporarily. When enabled, Nginx sends a response body containing a refresh meta tag (<meta http-equiv=”Refresh”…>) to the clients running an MSIE browser in order to redirect the browser to the new location of the requested resource.
Syntax: on or off Default value: off resolver
Context: http, server, location
This directive specifies the name servers that should be employed by Nginx to resolve hostnames to IP addresses and vice versa. DNS query results are cached for some time, either by respecting the TTL provided by the DNS server, or by specifying a time value to the valid argument.
Syntax: one or more IPv4 or IPv6 addresses, valid=Time value, ipv6=on|off
Default value: None (system default)
resolver 127.0.0.1; # use local DNS
resolver 8.8.8.8 8.8.4.4 valid=1h; # use Google DNS and cache results for 1 hour
resolver_timeout
Context: http, server, location Timeout for a hostname resolution query. Syntax: Time value (in seconds)
Default value: 30
server_tokens
Context: http, server, location
This directive allows you to define whether or not Nginx should inform clients of the running version number. There are two situations where Nginx indicates its version number:
In the server header of HTTP responses (such as nginx/1.8.0). If you set
server_tokens to off, the server header will only indicate Nginx.
On error pages, Nginx indicates the version number in the footer. If you set
server_tokens to off, the footer of error pages will only indicate Nginx.
If you are running an older version of Nginx and do not plan to update it, it might be a good idea to hide your version number for security reasons.
Syntax: on or off
Default value: on underscores_in_headers Context: http, server
This directive allows or disallows underscores in custom HTTP header names. If this directive is set to on, the following example header is considered valid by Nginx: test_header: value.
Syntax: on or off
Default value: off variables_hash_max_size Context: http
This directive defines the maximum size of the variables hash tables. If your server configuration uses a total of more than 1024 variables, you will have to increase this value.
Syntax: Numeric value Default value: 1024
variables_hash_bucket_size
Context: http
This directive allows you to set the bucket size for the variables hash tables. Syntax: Numeric value
Default value: 64 (or 32 or 128, depending on your processor cache specifications)
post_action
Context: http, server, location, if
The post_action directive defines a post-completion action, a URI that will be called by
Nginx after the request has been completed. Syntax: URI or named location block.
Example:
location /payment/ {
post_action /scripts/done.php;
}
Module variables
The HTTP Core module introduces a large set of variables that you can use within the value of directives. Be careful though, as only a handful of directives accept variables in the definition of their value. If you insert a variable in the value of a directive that does not accept variables, no error is reported; instead, the variable name appears as raw text.
There are three different kinds of variables that you will come across. The first set represents the values transmitted in the headers of the client request. The second set corresponds to the headers of the response sent to the client. Finally, the third set comprises variables that are completely generated by Nginx.
Request headers
Nginx lets you access client request headers under the form of variables that you will be able to employ later on in the configuration:
Variable |
Description |
$http_host |
Value of the Host HTTP header, a string indicating the hostname that the client is trying to reach. |
$http_user_agent |
Value of the User-Agent HTTP header, a string indicating the web browser of the client. |
$http_referer |
Value of the Referer HTTP header, a string indicating the URL of the previous page from which the client comes. |
$http_via |
Value of the Via HTTP header, which informs us about the possible proxies used by the client. |
$http_x_forwarded_for |
Value of the X-Forwarded-For HTTP header, which shows the actual IP address of the client if the client is behind a proxy. |
$http_cookie |
Value of the Cookie HTTP header, which contains the cookie data sent by the client. |
$http_… |
Additional headers sent by the client can be retrieved using $http_ followed by the header name in lowercase and with dashes (–) replaced by underscores (_). |
Response headers
In a similar fashion, you are allowed to access the HTTP headers of the response that was sent to the client. These variables are not available at all times—they will only carry a value after the response is sent, for instance, at the time of writing messages in the logs.
Variable |
Description |
$sent_http_content_type |
Value of the Content-Type HTTP header indicating the MIME type of the resource being transmitted. |
$sent_http_content_length |
Value of the Content-Length HTTP header informing the client of the response body length. |
$sent_http_location |
Value of the Location HTTP header, which indicates that the location of the desired resource is different from the one specified in the original request. |
$sent_http_last_modified |
Value of the Last-Modified HTTP header corresponding to the modification date of the requested resource. |
$sent_http_connection |
Value of the Connection HTTP header defining whether the connection will be kept alive or closed. |
$sent_http_keep_alive |
Value of the Keep-Alive HTTP header that defines the amount of time a connection will be kept alive. |
$sent_http_transfer_encoding |
Value of the Transfer-Encoding HTTP header giving information about the response body encoding method (such as compress, gzip). |
$sent_http_cache_control |
Value of the Cache-Control HTTP header, telling us whether the client browser should cache the resource or not. |
$sent_http_… |
Additional headers sent to the client can be retrieved using $sent_http_ followed by the header name in lowercase and with dashes (–) replaced by underscores (_). |
Nginx generated
Apart from the HTTP headers, Nginx provides a large number of variables concerning the request, the way it was and will be handled, as well as the settings in use with the current configuration.
Variable |
Description |
$arg_XXX |
Allows you to access the query string (GET parameters), where XXX is the name of the parameter that you wish to utilize. |
$args |
All the arguments of the query string combined together. |
$binary_remote_addr |
IP address of the client as binary data (4 bytes). |
$body_bytes_sent |
The number of bytes sent in the body of the response (does not include the response headers). |
$bytes_sent |
The number of bytes sent to the client. |
$connection |
Serial number identifying a connection. |
$connection_requests |
The number of requests already served by the current connection. |
$content_length |
Equates to the Content-Length HTTP header. |
$content_type |
Equates to the Content-Type HTTP header. |
$cookie_XXX |
Allows you to access cookie data, where XXX is the name of the parameter that you wish to utilize. |
$document_root |
Returns the value of the root directive for the current request. |
$document_uri |
Returns the current URI of the request. This may differ from the original request URI if internal redirects were performed. It is identical to the $uri variable. |
$host |
This variable equates to the Host HTTP header of the request. Nginx itself gives this variable a value for cases where the Host header is not provided in the original request. |
$hostname |
Returns the system hostname of the server computer |
$https |
Set to on for HTTPS connections, empty otherwise. |
$is_args |
If the $args variable is defined, $is_args equates to ?. If $args is empty, $is_args is empty as well. You may use this variable for constructing a URI that comes with a query string option, such as index.php$is_args$args. If there is any query string argument in the request, $is_args is set to ?, making this a valid URI. |
$limit_rate |
Returns the per-connection transfer rate limit as defined by the limit_rate directive. You are allowed to edit this variable by using set (directive from The Rewrite module): set $limit_rate 128k; |
$msec |
Returns the current time (in seconds + milliseconds). |
$nginx_version |
Returns the version of Nginx that you are running. |
$pid |
Returns the Nginx process identifier. |
$pipe |
If the current request is pipelined, this variable is set to p, otherwise the value is “.“. |
$proxy_protocol_addr |
If the proxy_protocol parameter is enabled on the listen directive, this variable will contain the client address. |
$query_string |
Identical to $args. |
$remote_addr |
Returns the IP address of the client. |
$remote_port |
Returns the port of the client socket. |
$remote_user |
Returns the client username if they use authentication. |
$realpath_root |
Returns the document root in the client request with symbolic links resolved into the actual path. |
$request_body |
Returns the body of the client request, or – if the body is empty. |
$request_body_file |
If the request body was saved (see the client_body_in_file_only directive), this variable indicates the path of the temporary file. |
$request_completion |
Returns OK if the request is completed, an empty string otherwise. |
$request_filename |
Returns the full filename served in the current request. |
$request_length |
Returns the total length of the client request. |
$request_method |
Indicates the HTTP method used in the request, such as GET or POST. |
$request_time |
Returns the amount of time elapsed since the first byte was read from the client (seconds + milliseconds value). |
$request_uri |
Corresponds to the original URI of the request, remains unmodified throughout the process (unlike $document_uri/$uri). |
$scheme |
Returns either http or https depending on the request. |
$server_addr |
Returns the IP address of the server. Beware while using this, as each use of the variable requires a system call, which could potentially affect the overall performance in the case of high-traffic setups. |
$server_name |
Indicates the value of the server_name directive that was used while processing the request. |
$server_port |
Indicates the port of the server socket that received the request data. |
$server_protocol |
Returns the protocol and version, usually HTTP/1.0 or HTTP/1.1. |
$status |
Returns the response status code. |
$tcpinfo_rtt, $tcpinfo_rttvar, |
If your operating system supports the TCP_INFO socket option, these variables will be |
$tcpinfo_snd_cwnd, $tcpinfo_rcv_space |
populated with information on the current client TCP connection. |
$time_iso8601, $time_local |
Provides the current time in ISO 8601 and local formats respectively for use with the access_log directive. |
$uri |
Identical to $document_uri. |
The location block
We have established that Nginx offers you the possibility to fine-tune your configuration down to three levels—at the protocol level (http block), the server level (server block), and the requested URI level (location block). Let us now detail the latter.
Location modifier
Nginx allows you to define location blocks by specifying a pattern that will be matched against the requested document URI.
server {
server_name website.com; location /admin/ {
# The configuration you place here only applies to # http://website.com/admin/
}
}
Instead of a simple folder name, you can indeed insert complex patterns. The syntax of the
location block is:
location [=|~|~*|^~|@] pattern { … }
The first optional argument is a symbol called location modifier that defines the way Nginx matches the specified pattern, and also defines the very nature of the pattern (simple string or regular expression). The following paragraphs detail the different modifiers and their behavior.
The = modifier
The requested document URI must match the specified pattern exactly. The pattern here is limited to a simple literal string; you cannot use a regular expression:
server {
server_name website.com; location = /abcd {
[…]
}
}
The configuration in the location block:
Applies to http://website.com/abcd (exact match)
May apply to http://website.com/ABCD (it is only case-sensitive if your operating system uses a case-sensitive filesystem)
Applies to http://website.com/abcd?param1¶m2 (regardless of the query string arguments)
Does not apply to http://website.com/abcd/ (trailing slash)
Does not apply to http://website.com/abcde (extra characters after the specified pattern)
No modifier
The requested document URI must begin with the specified pattern. You may not use regular expressions:
server {
server_name website.com;
location /abcd { […]
}
}
The configuration in the location block:
Applies to http://website.com/abcd (exact match)
May apply to http://website.com/ABCD (it is only case-sensitive if your operating system uses a case-sensitive filesystem)
Applies to http://website.com/abcd?param1¶m2 (regardless of the query string arguments)
Applies to http://website.com/abcd/ (trailing slash)
Applies to http://website.com/abcde (extra characters after the specified pattern)
The ~ modifier
The requested URI must be a case-sensitive match to the specified regular expression:
server {
server_name website.com; location ~ ^/abcd$ {
[…]
}
}
The ^/abcd$ regular expression used in this example specifies that the pattern must begin (^) with /, be followed by abc, and finish ($) with d. Consequently, the configuration in the location block:
Applies to http://website.com/abcd (exact match)
Does not apply to http://website.com/ABCD (case-sensitive)
Applies to http://website.com/abcd?param1¶m2 (regardless of the query string arguments)
Does not apply to http://website.com/abcd/ (trailing slash) due to the specified regular expression
Does not apply to http://website.com/abcde (extra characters) due to the specified regular expression
Note
With operating systems such as Microsoft Windows, ~ and ~* are both case-insensitive, as the OS uses a case-insensitive filesystem.
The ~* modifier
The requested URI must be a case-insensitive match to the specified regular expression:
server {
server_name website.com; location ~* ^/abcd$ { […]
}
}
The regular expression used in the example is similar to the previous one. Consequently, the configuration in the location block:
Applies to http://website.com/abcd (exact match) Applies to http://website.com/ABCD (case-insensitive)
Applies to http://website.com/abcd?param1¶m2 (regardless of the query string arguments)
Does not apply to http://website.com/abcd/ (trailing slash) due to the specified regular expression
Does not apply to http://website.com/abcde (extra characters) due to the specified regular expression
The ^~ modifier
Similar to the no-symbol behavior, the location URI must begin with the specified pattern. The difference is that if the pattern is matched, Nginx stops searching for other patterns (read the following section about search order and priority).
The @ modifier
Defines a named location block. These blocks cannot be accessed by the client but only by internal requests generated by other directives such as try_files or error_page.
Search order and priority
Since it’s possible to define multiple location blocks with different patterns, you need to understand that when Nginx receives a request, it searches for the location block that best matches the requested URI:
server {
server_name website.com; location /files/ {
# applies to any request starting with “/files/”
# for example /files/doc.txt, /files/, /files/temp/
}
location = /files/ {
# applies to the exact request to “/files/”
# and as such does not apply to /files/doc.txt # but only /files/
}
}
When a client visits http://website.com/files/doc.txt, the first location block applies. However, when they visit http://website.com/files/, the second block applies (even though the first one matches), because it has priority over the first one (it is an exact match).
The order you established in the configuration file (placing the /files/ block before the =
/files/ block) is irrelevant. Nginx will search for matching patterns in a specific order:
location blocks with the = modifier: If the specified string exactly matches the requested URI, Nginx retains the location block.
location blocks with no modifier: If the specified string exactly matches the requested URI, Nginx retains the location block.
location blocks with the ^~ modifier: If the specified string matches the beginning of the requested URI, Nginx retains the location block.
location blocks with ~ or ~* modifier: If the regular expression matches the requested URI, Nginx retains the location block.
location blocks with no modifier: If the specified string matches the beginning of the requested URI, Nginx retains the location block.
In that context, the ^~ modifier begins to make sense, and we can envision cases where it would be useful.
Case 1
Let’s begin by a simple example:
server {
server_name website.com; location /doc {
[…] # requests beginning with “/doc”
}
location ~* ^/document$ {
[…] # requests exactly matching “/document”
}
}
You might wonder: when a client requests http://website.com/document, which of these two location blocks applies? Indeed, both blocks match this request. Again, the answer does not lie in the order in which the blocks appear in the configuration files. In this case, the second location block will apply as the ~* modifier has priority over the other.
Case 2
We will now take a look at this second example:
server {
server_name website.com; location /document {
[…] # requests beginning with “/document”
}
location ~* ^/document$ {
[…] # requests exactly matching “/document”
}
}
The question remains the same—what happens when a client sends a request to download http://website.com/document? There is a trick here. The string specified in the first block now exactly matches the requested URI. As a result, Nginx prefers it over the regular expression.
Case 3
Finally, let’s go over a third and last scenario:
server {
server_name website.com; location ^~ /doc {
[…] # requests beginning with “/doc”
}
location ~* ^/document$ {
[…] # requests exactly matching “/document”
}
}
This last case makes use of the ^~ modifier. Which block applies when a client visits http://website.com/document? The answer is: the first block. The reason being that ^~ has priority over ~*. As a result, any request with a URI beginning with /doc will be affected to the first block, even if the request URI matches the regular expression defined in the second block.
……………….
//user any name you want but by default its nginx (www-data is apache term)
you can change different user like raaz, then your php-fpm user also raaz, no need to change mysql user. directory permission must be assigned to the user ex: raaz to www directory.
ex: sudo chown raaz:raaz -R var/www/html