Beginner’s Guide新手指南

Starting, Stopping, and Reloading Configuration启动、停止和重新加载配置
Configuration File’s Structure配置文件的结构
Serving Static Content提供静态内容
Setting Up a Simple Proxy Server设置简单的代理服务器
Setting Up FastCGI Proxying设置FastCGI代理

This guide gives a basic introduction to nginx and describes some simple tasks that can be done with it. 本指南对nginx进行了基本介绍,并介绍了使用nginx可以完成的一些简单任务。It is supposed that nginx is already installed on the reader’s machine. 据推测,nginx已经安装在读卡器的机器上。If it is not, see the Installing nginx page. 如果不是,请参阅安装nginx页面。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配置为代理服务器,以及如何将其与FastCGI应用程序连接。

nginx has one master process and several worker processes. nginx有一个主进程和几个工作进程。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. nginx采用基于事件的模型和依赖于操作系统的机制在工作进程之间高效地分配请求。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).工作进程的数量在配置文件中定义,可以针对给定配置进行固定,也可以根据可用CPU内核的数量进行自动调整(请参阅工作进程)。

The way nginx and its modules work is determined in the configuration file. nginx及其模块的工作方式在配置文件中确定。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.conf,并放置在目录/usr/local/nginx/conf/etc/nginx/usr/local/etc/nginx中。

Starting, Stopping, and Reloading Configuration启动、停止和重新加载配置

To start nginx, run the executable file. 要启动nginx,请运行可执行文件。Once nginx is started, it can be controlled by invoking the executable with the -s parameter. nginx启动后,可以通过使用-s参数调用可执行文件来控制它。Use the following syntax:使用以下语法:

nginx -s signal

Where signal may be one of the following:其中,signal可能是以下之一:

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. 在将重新加载配置的命令发送到nginx或重新启动之前,不会应用在配置文件中所做的更改。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. kill实用程序等Unix工具的帮助下,还可以向nginx进程发送信号。In this case a signal is sent directly to a process with a given process ID. 在这种情况下,信号直接发送到具有给定进程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. 默认情况下,nginx主进程的进程ID写入/usr/local/nginx/logs/var/run目录下的nginx.pidFor example, if the master process ID is 1628, to send the QUIT signal resulting in nginx’s graceful shutdown, execute:例如,如果主进程ID为1628,要发送导致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.有关向nginx发送信号的更多信息,请参阅控制nginx

Configuration File’s Structure配置文件的结构

nginx consists of modules which are controlled by directives specified in the configuration file. nginx由配置文件中指定的指令控制的模块组成。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).如果块指令可以在大括号内包含其他指令,则称为上下文(例如:事件http服务器位置)。

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.eventhttp指令位于main上下文、http中的serverserver中的location

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). web服务器的一项重要任务是提供文件(如图像或静态HTML页面)。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). 您将实现一个示例,其中根据请求,将从不同的本地目录:/data/www(可能包含HTML文件)和/data/images(包含图像)提供文件。This will require editing of the configuration file and setting up of a server block inside the http block with two location blocks.这将需要编辑配置文件,并在http块内设置一个服务器块,其中包含两个位置块。

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. 默认配置文件已经包含了server块的几个示例,大部分都被注释掉了。For now comment out all such blocks and start a new server block:现在,注释掉所有这些块并启动一个新的server块:

http {
    server {
    }
}

Generally, the configuration file may include several server blocks distinguished by ports on which they listen to and by server names. 通常,配置文件可能包括多个server块,这些服务器块由它们侦听的端口和服务器名称区分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.一旦nginx决定哪个服务器处理一个请求,它将根据server块中定义的location指令的参数测试请求头中指定的URI。

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. location块指定与请求的URI相比的“/”前缀。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. 对于匹配请求,URI将添加到root指令中指定的路径,即到/data/www,以形成本地文件系统上请求文件的路径。If there are several matching location blocks nginx selects the one with the longest prefix. 如果有多个匹配的location块,nginx将选择前缀最长的位置块。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块提供长度为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/. 这已经是在标准端口80上侦听的服务器的工作配置,并且可以在本地计算机上访问http://localhost/In response to requests with URIs starting with /images/, the server will send files from the /data/images directory. 为了响应URI以/images/开头的请求,服务器将从/data/images目录发送文件。For example, in response to the http://localhost/images/example.png request nginx will send the /data/images/example.png file. 例如,响应http://localhost/images/example.png请求,nginx将发送/data/images/example.png文件。If such file does not exist, nginx will send a response indicating the 404 error. 如果该文件不存在,nginx将发送一个指示404错误的响应。Requests with URIs not starting with /images/ will be mapped onto the /data/www directory. URI不是以/images/开头的请求将映射到/data/www目录。For example, in response to the http://localhost/some/example.html request nginx will send the /data/www/some/example.html file.例如,响应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 in access.log and error.log files in the directory /usr/local/nginx/logs or /var/log/nginx.如果某项功能无法按预期工作,您可以尝试在/usr/local/nginx/logs/var/log/nginx目录下的access.logerror.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. 这将是一个简单的服务器,它侦听端口8080(以前,自从使用标准端口80以来,没有指定listen指令),并将所有请求映射到本地文件系统上的/data/up1目录。Create this directory and put the index.html file into it. 创建此目录并将index.html文件放入其中。Note that the root directive is placed in the server context. 请注意,root指令位于服务器上下文中。Such root directive is used when the location block selected for serving a request does not include own root directive.当为服务请求而选择的location块不包括自己的root指令时,使用这样的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. 我们将修改第二个location块,它当前将带有/images/前缀的请求映射到/data/images目录下的文件,以使其与具有典型文件扩展名的图像请求相匹配。The modified location block looks like this:修改后的location块如下所示:

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

The parameter is a regular expression matching all URIs ending with .gif, .jpg, or .png. 该参数是一个正则表达式,匹配以.gif.jpg.png结尾的所有URI。A regular expression should be preceded with ~. 正则表达式前面应加上~The corresponding requests will be mapped to the /data/images directory.相应的请求将映射到/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. 当nginx选择一个location块为请求提供服务时,它首先检查指定前缀的location指令,记住前缀最长的位置,然后检查正则表达式。If there is a match with a regular expression, nginx picks this location or, otherwise, it picks the one remembered earlier.如果存在与正则表达式的匹配,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 reload 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服务器,该服务器运行使用各种框架和编程语言(如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. 使用FastCGI服务器最基本的nginx配置包括使用fastcgi_pass指令而不是proxy_pass指令,以及使用fastcgi_param指令来设置传递给FastCGI服务器的参数。Suppose the FastCGI server is accessible on localhost:9000. 假设FastCGI服务器可以在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. 以上一节中的代理配置为基础,将proxy_pass指令替换为fastcgi_pass指令,并将参数更改为localhost:9000In PHP, the SCRIPT_FILENAME parameter is used for determining the script name, and the QUERY_STRING parameter is used to pass request parameters. 在PHP中,SCRIPT_FILENAME参数用于确定脚本名称,QUERY_STRING参数用于传递请求参数。The resulting configuration would be:由此产生的配置将是:

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.这将设置一个服务器,该服务器将通过FastCGI协议将除静态映像请求之外的所有请求路由到在localhost:9000上运行的代理服务器。