您的位置:首页 > 运维架构 > Nginx

Nginx:配置指南(1)

2016-07-29 00:00 627 查看

Beginner’s Guide

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

nginx has one master process and several worker processes. Themain purpose of the master process is to read and evaluate configuration,andmaintain worker processes.Worker processes do actual processing of requests. nginx employs event-based model and OS-dependent mechanisms to efficiently distribute requests among worker processes. The number of worker processes is defined in the configuration file and may be fixed for a given configuration or automatically adjusted to the number of available CPU cores (see worker_processes).

The way nginx and its modules work is determined in the configuration file. By default, the configuration file is named
nginx.conf
and placed in the directory
/usr/local/nginx/conf
,
/etc/nginx
, or
/usr/local/etc/nginx
.


Starting, Stopping, and Reloading Configuration

To start nginx, run the executable file. Once nginx is started, it can be controlled by invoking the executable with the
-s
parameter. Use the following syntax:

nginx-s signal 


Where signal may be one of the following:

stop
— fast shutdown

quit
— graceful shutdown

reload
— reloading the configuration file

reopen
— reopening the log files

For example, to stop nginx processes with waiting for the worker processes to finish serving current requests, the following command can be executed:

nginx-s quit 


This command should be executed under the same user that started nginx.

Changes made in the configuration file will not be applied until the command to reload configuration is sent to nginx or it is restarted. To reload configuration, execute:

nginx-s reload 


Once the master process receives the signal to reload configuration, it checks the syntax validity of the new configuration file and tries to apply the configuration provided in it. If this is a success, the master process starts new worker processes and sends messages to old worker processes, requesting them to shut down. Otherwise, the master process rolls back the changes and continues to work with the old configuration. Old worker processes, receiving a command to shut down, stop accepting new connections and continue to service current requests until all such requests are serviced. After that, the old worker processes exit.

A signal may also be sent to nginx processes with the help of Unix tools such as the
kill
utility. In this case a signal is sent directly to a process with a given process ID.The process ID of the nginx master process is written, by default, to the
nginx.pid
in the directory
/usr/local/nginx/logs
or
/var/run
.
For example, if the master process ID is 1628, to send the QUIT signal resulting in nginx’s graceful shutdown, execute:

kill-s QUIT 1628 


For getting the list of all running nginx processes, the
ps
utility may be used, for example, in the following way:

ps -ax | grep nginx


For more information on sending signals to nginx, seeControlling nginx.

Configuration File’s Structure

nginx consists of modules which are controlled by directives specified in the configuration file. Directives are divided into simple directives and block directives. A simple directive consists of the name and parameters separated by spaces and ends with a semicolon (
;
). A block directive has the same structure as a simple directive, but instead of the semicolon it ends with a set of additional instructions surrounded by braces (
{
and
}
). If a block directive can have other directives inside braces, it is called a context (examples:events,http,server, and location).

Directives placed in the configuration file outside of any contexts are considered to be in th emain context. The
events
and
http
directives reside in the
main
context,
server
in
http
, and
location
in
server
.

The rest of a line after the
#
sign is considered a comment.

Serving Static Content

An important webserver task is serving out files (such as images or static HTML pages). You will implement an example where, depending on the request, files will be served from different local directories:
/data/www
(which may contain HTML files) and
/data/images
(containing images). This will require editing of the configuration file and setting up of aserver block inside the http block with two location blocks.

First, create the
/data/www
directory and put an
index.html
file with any text content into it and create the
/data/images
directory and place some images in it.

Next, open the configuration file. The default configuration file already includes several examples of the
server
block, mostly commented out. For now comment out all such blocks and start a new
server
block:

http {server { } }


Generally, the configuration file may include several
server
blocksdistinguished by ports on which they listen to and by server names. Once nginx decides which
server
processes a request, it tests the URI specified in the request’s header against the parameters of the
location
directives defined inside the
server
block.


Add the following
location
block to the
server
block:

location / { root /data/www; }


This
location
block specifies the "
/"
prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in the root directive, that is, to
/data/www
, to form the path to the requested file on the local file system.If there are several matching
location
blocks nginx selects the one with the longest prefix.
The
location
block above provides the shortest prefix, of length one, and so only if all other
location
blocks fail to provide a match, this block will be used.

Next, add the second
location
block:

location /images/ { root /data; }


It will be a match for requests starting with
/images/
(
location /
also matches such requests, but has shorter prefix).

The resulting configuration of the
server
block should look like this:

server {location / { root /data/www; }location /images/ { root /data; }} 


This is already a working configuration of aserver thatlistens on the standard port 80 and is accessible on the local machine at
http:/
/
localhost
/
.In response to requests with URIs starting with
/images/
, theserver will send files from the
/data/images
directory.
For example, in response to the
http://localhost/images/example.png
request nginx will send the
/data/images/example.png
file. If such file does not exist, nginx will send a response indicating the 404 error. Requests with URIs not starting with
/images/
will be mapped onto the
/data/www
directory. For example, in response to the
http://localhost/some/example.html
request nginx will send the
/data/www/some/example.html
file.

To apply the new configuration, start nginx if it is not yet started or send the
reload
signal to the nginx’s master process, by executing:

nginx-s reload 


In case something does not work as expected, you may try to find out the reason in
access.log
and
error.log
files in the directory
/usr/local/nginx/logs
or
/var/log/nginx
.


Setting Up a Simple Proxy Server

One of the frequent uses of nginx is setting it up as a proxyserver, which means aserver that receives requests, passes them to the proxiedservers, retrieves responses from them, and sends them to the clients.

We will configure a basic proxyserver, which serves requests of images with files from the local directory and sends all other requests to a proxiedserver. In this example, bothservers will be defined on a single nginx instance.

First, define the proxiedserver by adding one more
server
block to the nginx’s configuration file with the following contents:

server {listen 8080; root /data/up1;location / { } } 


This will be a simpleserver thatlistens on the port 8080(previously, the
listen
directive has not been specified since the standard port 80 was used) and maps all requests to the
/data/up1
directory on the local file system. Create this directory and put the
index.html
file into it. Note that the
root
directive is placed in the
server
context.
Such
root
directive is used when the
location
block selected for serving a request does not include own
root
directive.

Next, use theserver configuration from the previous section and modify it to make it a proxyserver configuration. In the first
location
block, put the proxy_pass directive with the protocol, name and port of the proxiedserver specified in the parameter (in our case, it is
http://localhost:8080
):

server {location / { proxy_pass http://localhost:8080; }location /images/ { root /data; }} 


We will modify the second
location
block, which currently maps requests with the
/images/
prefix to the files under the
/data/images
directory, to make it match the requests of images with typical file extensions. The modified
location
block looks like this:

location ~ \.(gif|jpg|png)$ { root /data/images; }


The parameter is a regular expression matching all URIs ending with
.gif
,
.jpg
, or
.png
.
A regular expression should be preceded with
~
. The corresponding requests will be mapped to the
/data/images
directory.

When nginx selects a
location
block to serve a request it first checkslocation directives that specify prefixes, remembering
location
with the longest prefix, and then checks regular expressions. If there is a match with a regular expression, nginx picks this
location
or, otherwise, it picks the one remembered earlier.

The resulting configuration of a proxyserver will look like this:

server {location / { proxy_pass http://localhost:8080/; }location ~ \.(gif|jpg|png)$ { root /data/images; }} 


Thisserver will filter requests ending with
.gif
,
.jpg
, or
.png
and map them to the
/data/images
directory (by adding URI to the
root
directive’s parameter) and pass all other requests to the proxiedserver configured above.


To apply new configuration, send the
reload
signal to nginx as described in the previous sections.

There are many more directives that may be used to further configure a proxy connection.

Setting Up FastCGI Proxying

nginx can be used to route requests to FastCGIservers which run applications built with various frameworks and programming languages such as PHP.

The most basic nginx configuration to work with a FastCGIserver includes using thefastcgi_pass directive instead of the
proxy_pass
directive, and fastcgi_param directives to set parameters passed to a FastCGIserver.
Suppose the FastCGIserver is accessible on
localhost:9000
. Taking the proxy configuration from the previous section as a basis, replace the
proxy_pass
directive with the
fastcgi_pass
directive and change the parameter to
localhost:9000
. In PHP, the
SCRIPT_FILENAME
parameter is used for determining the script name, and the
QUERY_STRING
parameter is used to pass request parameters. The resulting configuration would be:

server {location / { fastcgi_passlocalhost:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_paramQUERY_STRING $query_string; }location ~ \.(gif|jpg|png)$ { root /data/images; }} 


This will set up aserver that will route all requests except for requests for static images to the proxiedserver operating on
localhost:9000
through the FastCGI protocol.

Controlling nginx

nginx can be controlled with signals. The process ID of the master process is written to the file
/usr/local/nginx/logs/nginx.pid
by default. This name may be changed at configuration time, or in
nginx.conf
using thepid directive.
The master process supports the following signals:

TERM, INTfast shutdown
QUITgraceful shutdown
HUPchanging configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes
USR1re-opening log files
USR2upgrading an executable file
WINCHgraceful shutdown of worker processes
Individual worker processes can be controlled with signals as well, though it is not required. The supported signals are:

TERM, INTfast shutdown
QUITgraceful shutdown
USR1re-opening log files
WINCHabnormal termination for debugging(requiresdebug_points to be enabled)

Changing Configuration

In order for nginx to re-read the configuration file, a HUP signal should be sent to the master process.The master process first checks the syntax validity, then tries to apply new configuration, that is, to open log files and newlisten sockets. If this fails, it rolls back changes and continues to work with old configuration. If this succeeds, it starts new worker processes, and sends messages to old worker processes requesting them to shut down gracefully. Old worker processes closelisten sockets and continue to service old clients. After all clients are serviced, old worker processes are shut down.

Let’s illustrate this by example. Imagine that nginx is run on FreeBSD 4.x and the command

ps axw -o pid,ppid,user,%cpu,vsz,wchan,command | egrep '(nginx|PID)'


produces the following output:

PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1148 pause nginx: master process /usr/local/nginx/sbin/nginx 33127 33126 nobody 0.0 1380 kqread nginx: worker process (nginx) 33128 33126 nobody 0.0 1364 kqread nginx: worker process (nginx) 33129 33126 nobody 0.0 1364 kqread nginx: worker process (nginx)


If HUP is sent to the master process, the output becomes:

PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1164 pause nginx: master process /usr/local/nginx/sbin/nginx 33129 33126 nobody 0.0 1380 kqread nginx: worker process is shutting down (nginx) 33134 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33135 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33136 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)


One of the old worker processes with PID 33129 still continues to work. After some time it exits:

PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1164 pause nginx: master process /usr/local/nginx/sbin/nginx 33134 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33135 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33136 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)


Rotating Log-files

In order to rotate log files, they need to be renamed first. After that USR1 signal should be sent to the master process. The master process will then re-open all currently open log files and assign them an unprivileged user under which the worker processes are running, as an owner. After successful re-opening, the master process closes all open files and sends the message to worker process to ask them to re-open files. Worker processes also open new files and close old files right away. As a result, old files are almost immediately available for post processing, such as compression.

Upgrading Executable on the Fly

In order to upgrade theserver executable, the new executable file should be put in place of an old file first. After that USR2 signal should be sent to the master process.The master process first renames its file with the process ID to a new file with the
.oldbin
suffix, e.g.
/usr/local/nginx/logs/nginx.pid.oldbin
, then starts a new executable file that in turn starts new worker processes:


PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1164 pause nginx: master process /usr/local/nginx/sbin/nginx 33134 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33135 33126 nobody 0.0 1380 kqread nginx: worker process (nginx) 33136 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 36264 33126 root 0.0 1148 pause nginx: master process /usr/local/nginx/sbin/nginx 36265 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36266 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36267 36264 nobody 0.0 1364 kqread nginx: worker process (nginx)


After that all worker processes (old and new ones) continue to accept requests. If the WINCH signal is sent to the first master process, it will send messages to its worker processes, requesting them to shutdown gracefully, and they will start to exit:

PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1164 pause nginx: master process /usr/local/nginx/sbin/nginx 33135 33126 nobody 0.0 1380 kqread nginx: worker process is shutting down (nginx) 36264 33126 root 0.0 1148 pause nginx: master process /usr/local/nginx/sbin/nginx 36265 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36266 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36267 36264 nobody 0.0 1364 kqread nginx: worker process (nginx)


When using the “rtsig” method on Linux, the new processes may not accept connections even after the old master process was sent the WINCH signal. If that is the case, the USR1 signal should be sent to the new master process continuously, until the new processes start to accept connections.

After some time, only the new worker processes will process requests:

PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1164 pause nginx: master process /usr/local/nginx/sbin/nginx 36264 33126 root 0.0 1148 pause nginx: master process /usr/local/nginx/sbin/nginx 36265 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36266 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36267 36264 nobody 0.0 1364 kqread nginx: worker process (nginx)


It should be noted that the old master process does not close itslisten sockets, and it can be managed to start its worker processes again if needed. If for some reason the new executable file works unacceptably, one of the following can be done:

Send the HUP signal to the old master process. The old master process will start new worker processes without re-reading the configuration. After that, all new processes can be shut down gracefully, by sending the QUIT signal to the new master process.

Send the TERM signal to the new master process. It will then send a message to its worker processes requesting them to exit immediately, and they will all exit almost immediately. (If new processes do not exit for some reason, the KILL signal should be sent to them to force them to exit.) When the new master process exits, the old master process will start new worker processes automatically.

If the new master process exits then the old master process discards the
.oldbin
suffix from the file name with the process ID.


If upgrade was successful, then the old master process should be sent the QUIT signal, and only new processes will stay:

PID PPID USER %CPU VSZ WCHAN COMMAND 36264 1 root 0.0 1148 pause nginx: master process /usr/local/nginx/sbin/nginx 36265 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36266 36264 nobody 0.0 1364 kqread nginx: worker process (nginx) 36267 36264 nobody 0.0 1364 kqread nginx: worker process (nginx)


Connection processing methods

nginx supports a variety of connection processing methods. The availability of a particular method depends on the platform used. On platforms that support several methods nginx will normally select the most efficient method automatically. However, if needed, a connection processing method can be selected explicitly with the use directive.

The following connection processing methods are supported:

select
— standard method. The supporting module is built automatically on platforms that lack more efficient methods. The
--with-select_module
and
--without-select_module
configuration parameters can be used to forcibly enable or disable the build of this module.

poll
— standard method. The supporting module is built automatically on platforms that lack more efficient methods. The
--with-poll_module
and
--without-poll_module
configuration parameters can be used to forcibly enable or disable the build of this module.

kqueue
— efficient method used on FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0, and Mac OS X.

epoll
— efficient method used onLinux 2.6+.

Some older distributions like SuSE 8.2 provide patches that add epoll support to 2.4 kernels.

rtsig
— real time signals, efficient method used on Linux 2.2.19+. By default, the system-wide event queue is limited by 1024 signals.On loadedservers it may become necessary to increase this limit by changing the
/proc/sys/kernel/rtsig-max
kernel parameter.
However, in Linux 2.6.6-mm2 this parameter is gone, and each process now has its own event queue. The size of each queue is limited by
RLIMIT_SIGPENDING
and can be changed with worker_rlimit_sigpending.
On queue overflow, nginx discards the queue and falls back to
poll
connection processing method until the situation gets back to normal.


/dev/poll
— efficient method used on Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+, and Tru64 UNIX 5.1A+.

eventport
— event ports, efficient methodused on Solaris 10.

Setting up hashes

To quickly process static sets of data such asserver names,map directive’s values, MIME types, names of request header strings, nginx uses hash tables.During the start and each re-configuration nginx selects the minimum possible sizes of hash tables such that the bucket size that stores keys with identical hash values does not exceed the configured parameter (hash bucket size). The size of a table is expressed in buckets. The adjustment is continued until the table size exceeds the hash max size parameter. Most hashes have the corresponding directives that allow changing these parameters, for example, for theserver names hash they areserver_names_hash_max_size andserver_names_hash_bucket_size.
The hash bucket size parameter is aligned to the size that is a multiple of the processor’s cache line size. This speeds up key search in a hash on modern processors by reducing the number of memory accesses. If hash bucket size is equal to one processor’s cache line size then the number of memory accesses during the key search will be two in the worst case — first to compute the bucket address, and second during the key search inside the bucket. Therefore, if nginx emits the message requesting to increase either hash max size or hash bucket size then the first parameter should first be increased.

Original: http://nginx.org/en/docs/ href="http://nginx.org/en/docs/beginners_guide.html" target=_blank>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: