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 proxy server, and how to connect it with a FastCGI application.
本指南介绍了nginx的基本知识,并介绍了一些可以使用nginx完成的简单任务。假设读者的计算机已经安装了nginx。如果没有,请参阅安装nginx页面。本指南介绍如何启动和停止nginx,重新加载其配置,解释配置文件的结构,介绍如何设置nginx用于提供静态内容,配置为代理服务器,以及如何与FastCGI应用程序结合使用。
nginx has one master process and several worker processes. The main purpose of the master process is to read and evaluate configuration, and maintain 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).
nginx有一个主进程和多个工作进程。主进程的主要目的是读取和检查配置,并维护工作进程。真正处理请求的则是工作进程。nginx采用基于事件的模型和依赖操作系统的机制,在工作进程间有效分配请求。工作进程的数量在配置文件中定义;可以根据设置固定数量,也可以根据可用CPU核数自动调整(参见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
.
nginx及其模块的工作方式由配置文件决定,通常情况下配置文件名为nginx.conf
,通常位于/usr/local/nginx/conf
,
/etc/nginx
, 或者
/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:
-s
通过执行文件来控制。使用语法如下:
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进程,等待工作进程完成当前请求,可执行如下命令
nginx -s quit
This command should be executed under the same user that started nginx.
执行此命令的用户需要和启动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发送重新载入配置文件的指令
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:
也可以借助Unix工具(如kill
工具)向nginx进程发送信号。在这种情况下,信号会直接发送到指定进程ID的进程。nginx主进程的进程ID默认写入/usr/local/nginx/logs
或/var/run
目录下的nginx.pid
。例如,如果主进程ID是1628,要发送QUIT信号使nginx优雅关闭,执行如下:
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:
获取正在运行的nginx所有进程,可以使用ps
工具,比如:
ps -ax | grep nginx
For more information on sending signals to nginx, see Controlling nginx.
想了解更多向ngix发送信号的内容,可以参看控制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).
nginx由模块组成,模块由配置文件中的指令控制。指令分为简单指令和块指令。简单指令由名称和参数组成,以空格分隔,以分号( ; )结束。块指令的结构与简单指令相同,但它的结尾不是分号,而是用大括号( { } )包围的一组附加指令。如果一条块指令的大括号内还包含其他指令,则称为上下文(例如:events、http、server,和location)。
Directives placed in the configuration file outside
of any contexts are considered to be in the
main context.
The events
and http
directives
reside in the main
context, server
in http
, and location
in
server
.
在配置文件中,除了在具体上下文之间的指令,其余均视为在基本配置中。events
和http
指令位于主上下文中(main context)
,server
位于http
中,location
位于server
中。
The rest of a line after the #
sign is considered a comment.
#
号之后的部分被视为注释
Serving Static Content
提供静态内容
An important web server 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 a
server
block inside the http
block with two location
blocks.
Web服务器的一项重要任务是文件的展示(如图像或静态HTML页面)。接下来将完成一个示例配置。根据请求,将从不同的本地目录提供文件:/data/www(可能包含HTML文件)和/data/images(包含图片)。这需要编辑配置文件,并在http块内设置一个包含两个location模块的server模块。
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.
首先,创建/data/www
目录,并在其中放置一个包含任何文本内容的index.html
文件,然后创建/data/images
目录,并在其中放置一些图片。
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:
接着打开配置文件。默认配置文件中已经包含了几个server
代码块的示例。现在先注释掉所有这些代码块,然后启动一个新的server
代码块,如:
http { server { } }
Generally, the configuration file may include several
server
blocks
distinguished 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.
一般来说,配置文件中可能包含多个server
块,这些服务器(server)块按监听(listen)端口和服务器名(server names)区分(distinguished)。一旦确定了处理请求的server
模块,nginx就会根据头中指定的URI,尝试使用location
中指令参数进行响应。
Add the following location
block to the
server
block:
将如下location
块添加到server
中
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.
该location
块指定"/"前缀,并与请求中的URI相比较。对于匹配的请求,URI将被添加到根(root)指令中指定的路径,即/data/www
,以形成本地文件系统中请求文件的路径。如果有多个匹配的location
,nginx会选择前缀最长的location
。上面的location
提供了长度为1的最短前缀,因此只有在其他location
都无法匹配时,才会使用该位置块。
Next, add the second location
block:
接着添加第二个location
块
location /images/ { root /data; }
It will be a match for requests starting with /images/
(location /
also matches such requests,
but has shorter prefix).
它将匹配以/images/
开头的请求(location /
也匹配此类请求,但匹配前缀更短)。
The resulting configuration of the server
block should
look like this:
最终,server
模块的配置结果应如下所示:
server { location / { root /data/www; } location /images/ { root /data; } }
This is already a working configuration of a server that listens
on the standard port 80 and is accessible on the local machine at
http://localhost/
.
In response to requests with URIs starting with /images/
,
the server 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.
这已经是一个监听标准80端口,并可在本地计算机上通过http://localhost/
访问的可以运行的服务器配置。它对于以/images/
开头的 URI 请求,服务器将发送/data/images
目录中的文件。例如,在响应http://localhost/images/example.png
请求时,nginx将发送/data/images/example.png
文件作为响应。如果该文件不存在,nginx将发送404错误响应。URI不以/images/
开头的请求将被映射到/data/www
目录。例如,在响应http://localhost/some/example.html
请求时,nginx 将发送/data/www/some/example.html
文件。
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尚未启动,则启动nginx,或者向nginx主进程发送重载(reload)
配置文件的信号,方法是执行:
nginx -s reload
In case something does not work as expected, you may try to find out the reason inaccess.log
anderror.log
files in the directory/usr/local/nginx/logs
or/var/log/nginx
.如果出现与预期不符的情况,可以尝试在
/usr/local/nginx/logs
或/var/log/nginx
目录下的access.log
和error.log
文件中查找原因。
Setting Up a Simple Proxy Server
设置一个简单的代理服务器
One of the frequent uses of nginx is setting it up as a proxy server, which means a server that receives requests, passes them to the proxied servers, retrieves responses from them, and sends them to the clients.
nginx的一个常用用于是将其设置为代理服务器。这意味着服务器接收请求,将请求传递给代理服务器,代理服务器获取响应,然后代理服务器将响应发送给客户端。
We will configure a basic proxy server, which serves requests of images with files from the local directory and sends all other requests to a proxied server. In this example, both servers will be defined on a single nginx instance.
我们将配置一个基本的代理服务器。该服务器用本地目录中的文件提供请求图像服务,而所有其他请求发送到代理服务器。在本例中,两个服务器都将定义在一个nginx实例上。
First, define the proxied server by adding one more server
block to the nginx’s configuration file with the following contents:
首先,在nginx配置文件中添加一个server
块,定义代理服务器,内容如下:
server { listen 8080; root /data/up1; location / { } }
This will be a simple server that listens 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 its own root
directive.
这将是一个简单的服务器,监听8080端口(之前未指定监听指令,使用是标准的80端口),并将所有请求映射到本地文件系统上的/data/up1
目录。创建该目录并将index.html
文件放入其中。请注意,root
指令被置于server
上下文中。当为请求提供服务location
块不包含在root
指令中时,才会使用这样的根指令。
Next, use the server configuration from the previous section
and modify it to make it a proxy server configuration.
In the first location
block, put the
proxy_pass
directive with the protocol, name and port of the proxied server specified
in the parameter (in our case, it is http://localhost:8080
):
接下来,使用上一节中的服务器配置,并将其修改为代理服务器配置。在第一个location
块中,放入proxy_pass指令,并在参数中指定代理服务器的协议、服务器名和端口(在本例中为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
块,它目前将 /images/
前缀的请求映射到/data/images
目录下的文件,使其请求与图像文件的扩展名相匹配。修改后的location
块如下所示:
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.
参数是匹配所有以.gif
、.jpg
或.png
结尾的URI的正则表达式。前面加上~
表示是正则表达式。相应的请求将被映射到/data/images
目录。
When nginx selects a location
block to serve a request
it first checks location
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.
nginx在选择location
块为请求提供服务时,首先会检查指定前缀的位置指令,记住前缀最长的location,然后检查正则表达式。如果与正则表达式匹配,nginx就会选择该location
,否则就会选择之前记住的前缀最长的位置。
The resulting configuration of a proxy server will look like this:
代理服务器的配置结果如下:
server { location / { proxy_pass http://localhost:8080/; } location ~ \.(gif|jpg|png)$ { root /data/images; } }
This server 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 proxied server configured above.
该服务器将.gif
、.jpg
或.png
结尾的请求,映射到/data/images
目录(将URI添加到root
指令参数中),并将所有其他请求传递给上述配置的代理服务器。
To apply new configuration, send the signal to nginx as described in the previous sections.
要应用新配置,请按照前述,向nginx发送reload
信号。
There are many more directives that may be used to further configure a proxy connection.
还有许多指令可进一步配置代理连接。
Setting Up FastCGI Proxying
设置FastCGI代理
nginx can be used to route requests to FastCGI servers which run applications built with various frameworks and programming languages such as PHP.
nginx可用于将请求路由到FastCGI服务器。FastCGI服务器可运行使用各种框架和编程语言(如PHP)构建的应用程序。
The most basic nginx configuration to work with a FastCGI server
includes using the
fastcgi_pass
directive instead of the proxy_pass
directive,
and fastcgi_param
directives to set parameters passed to a FastCGI server.
Suppose the FastCGI server 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:
nginx与FastCGI服务器配合使用最基本的方式是使用fastcgi_pass指令而并非proxy_pass
指令,fastcgi_param指令设置传递给FastCGI服务器的参数。假设FastCGI服务器的访问地址是localhost:9000
。以之前的代理配置为基础,用
fastcgi_pass
指令替换proxy_pass
指令,并将参数改为localhost:9000
。在PHP中,SCRIPT_FILENAME
参数用于确定脚本名称,QUERY_STRING
参数用于传递请求参数。配置参考如下
server { location / { fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; } location ~ \.(gif|jpg|png)$ { root /data/images; } }
This will set up a server that will route all requests except for
requests for static images to the proxied server operating on
localhost:9000
through the FastCGI protocol.
localhost:9000
上的服务器。