25 KiB
title: 初级教程 cover: https://res.ciduid.top/blog/covers/cover(8).jpg date: 2022-08-06 16:52:03
读nginx文档的时候突然想自己试着把文档翻一翻了...
这些翻译并没有严格按照英语语法去对应中文,而是经过自己的一点修改
翻译得并不是很好,只是自己学习文档的同时顺便翻译翻译,还请见谅....
将来会不定期更新的...要是哪天弃坑了也不是不可能...
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来分发静态内容
-
如何将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在运行中会创建一个master进程和若干个worker进程。master进程主要用于读取并验证配置文件以及worker进程的维护,而真正的请求则是由worker进程来处理。
nginx采用事件驱动模型以及系统相关机制来高效地将请求分发给各个worker进程,worker进程的数量被定义在配置文件中,但是,这个数量可能会固定为配置文件所设置的大小,也有可能会调整为可用的CPU内核数。详见:worker进程
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的配置文件默认为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:
要启动nginx,只需运行nginx的二进制可执行文件即可。nginx启动后,使用-s
参数调用可执行文件就能控制nginx的启停以及配置文件重载。以下是相关调用语法:
nginx -s signal
Where signal may be one of the following:
signal
应为一下几种情况:
-
stop
— 快速停止 -
quit
— “优雅”地停止 -
reload
— 重新加载配置文件 -
reopen
— 重新打开日志文件
For example, to stop nginx processes with waiting for the worker processes to finish serving current requests, the following command can be executed:
例如,要使nginx的worker进程结束完当前所有的请求之后再停止,应当这样执行:
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.
master进程一旦接收到这个重载配置文件的信号,其会检查配置文件语法的正确性然后尝试应用这些修改。如果成功,master进程则会启动新的worker进程并且将消息发送给旧的worker进程,要求其停止。否则master进程不会去应用这些更改,并继续以旧的配置来工作。
旧的worker进程收到关闭命令后,不会再接受新的连接请求,但仍在进行的请求仍会被处理,直到这些请求完成。最后,旧的worker进程就会退出。
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
等Unix工具来发送给nginx进程。这样就可以通过指定的PID来直接向nginx进程发送信号。这些nginx PID默认记录在nginx.pid
文件中,该文件一般位于/usr/local/nginx/logs
或/var/run
文件夹中。
例如,master进程的PID为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.
想要了解更多的关于将信号发送至nginx进程的方法,详见:控制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是由多个模块构成的,而这些模块是由配置文件中设定的指令控制的。
这些指令分成数个基本指令和指令块。一条基本指令包括指令名及若干个以空格分隔的参数,并且以;
(分号)结束。指令块跟基本指令有相似的结构,但跟基本指令不同的是,指令块不以分号结束,而是以一组大括号括起来的附加指令结束。如果一个指令块的大括号里边包括有其他的指令,则会被称为~~“context”~~(姑且也成为块吧...)(例如: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
.
The rest of a line after the #
sign is considered a comment.
放置在任何块之外的指令被视作是放置于main块当中。events
和http
指令块是放在main块中的;server
块是放在http
块中的;而location
块则又放置在server
块中
在一行中以#
开始的部分则会被视作注释。
处理静态内容请求 / 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.
传输文件(例如图像或者静态HTML页面之类的数据)是网络服务中非常重要的一部分。
你在这里将会实现一个根据请求来从本地目录/data/www
(包含了HTML文件)和/data/image
(包含了图像)对外分提供文件的例子。
这需要你编辑配置文件并在http块中设置一个server块,而在这个server块中又包含有两个location块。
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_name)来进行区分的,nginx会把在请求头中指定的URI参数与在server
块中location
指令的参数进行匹配。
Add the following location
block to the server
block:
在server
块添加一个像这样的location
块:
loaction / {
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
块指定了与之相配的URI路径/
。对于匹配到的请求,这个URI会被添加到在root指令中设定的路径,也就是/data/www
,以形成请求本地文件的路径。如有多个location
块能被匹配到,nginx会使用路径最长的那个location
块。上述示例中的location
块只提供了最短的路径,长度为1,所以在只有其他路径都匹配不到的时候才会被使用。
接着,添加第二个location
块:
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:
这能够使其匹配到以/images/
开头的请求(当然location /
也能被匹配到,但它的路径更短,所以不会被使用)。
最终这个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.
现在,这个server
块侦听在80端口上,在本地计算机通过地址http://localhost/
就能访问到。
对于以/images/
为开头的请求,服务器会从/data/images/
目录获取文件,并将文件数据返回。
- 例如:对于请求
http://localhost/images/example.png
,nginx将会把/data/images/example.png
文件发送出去。
如果文件不存在,nginx会发送表示404错误的响应。除了/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没有启动起来的话),或者通过执行以下命令来将reload
命令发送给nginx的master进程:
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
.
如果因为各种原因,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:
首先,新增一个server
块到nginx的配置文件中,像下面那样,以便新增一个被代理服务器:
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端口的服务器就成了(在之前的例子中,由于没有定义listen
,因此侦听的是默认的80端口),在这个服务器中,所有的请求都会映射到本地文件系统的/data/up1
目录中。把这个目录创建好,然后把index.html
放在里边。
这里的root
指令是放在server
部分的。像这种在location
外的root
指令是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
目录下,并且只匹配后缀为.gif
、.jpg
或.png
的文件请求。
修改后的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.
The resulting configuration of a proxy server will look like this:
当nginx选择用哪一个location
块来处理请求时,它首先检查指定路径的location指令,然后再检查用正则表达式的location
。如果有匹配,nginx会就选择这个用正则表达式作为参数的location
,否则就使用路径最长的location
块来处理请求。
最终的配置是这样的:
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.
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.
现在,这个server
能够处理以.gif
、.jpg
或.png
结尾的请求,并将它们映射到/data/images
目录(通过在root
指令的参数中添加URI路径作为真实文件路径),其他的请求就会转发到配置好的被代理服务器上。
要让配置生效,还是想上面那样,运行nginx -s reload
。
有很多指令可以用来进一步配置代理连接。
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.
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服务器,以便运行用各种框架和编程语言(如PHP)构建的应用程序。
在这里的配置中,代理转发用的是fastcgi_pass指令而不是proxy_pass
指令;fastcgi_param指令是用来设置传递给FastCGI服务器的参数。
假设我们的FastCGI服务器运行在localhost:9000
上。
以上一节的代理配置为基础,将proxy_pass
指令改成fastcgi_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.
这样,nginx就会通过FastCGI协议把所有的请求(除了那些图像的静态请求)路由到运行在localhost:9000
的FastCGI服务器上。