# “源产控”系列（二）在CentOS 8上使用Nginx 1.18: 编译安装与基本使用

> 作者：zning（https://ning.ae） · 发布：2020/07/07 18:10 下午 (UTC+8) · 原文：https://zning.me/15941166309027.html

> 本篇为慧响技术角“源产控”专题系列第2篇文章。

<!-- -->

> 慧响技术角“源产控”专题，将聚焦开源、国产化、自主可控三个方向的技术，以操作系统、中间件、数据库、程序应用等为粗分类，更新相关技术的发展趋势、探究技术核心的深度使用、系统总结技术整体架构，为对相关技术的学习者提供可观的资料，亦为个人同步学习总结的笔记，以飨读者。

本篇对在CentOS 8上使用Nginx 1.18的基本安装与基本使用进行介绍与总结，未来对在CentOS 8上使用Nginx 1.18的相关，将陆续更新其使用总结、性能调优等方面的系列文章，敬请期待。

## Nginx是个啥

Nginx（发音同“engine X”）是异步框架的网页服务器，也可以用作反向代理、负载平衡器和HTTP缓存。该软件由伊戈尔·赛索耶夫创建并于2004年首次公开发布。2011年成立同名公司以提供支持。2019年3月11日，Nginx公司被F5 Networks以6.7亿美元收购。Nginx是免费的开源软件，根据类BSD许可证的条款发布。一大部分Web服务器使用Nginx，通常作为负载均衡器。

其开源版本官网是nginx.org。商业版本官网是nginx.com。

不过说起来Nginx，就不得不提在Nginx被F5收购后Nginx作者被捕的事儿了。据外媒报道，2019年12月12日，俄罗斯警方搜查了商业服务器公司Nginx，并当场带走了两位联合创始人。。关于这个事儿，我在文章《战疫之下，哪些事可能会改变我们》也拿其为例对个人品牌与口碑塑造的一些风险进行了阐述。有兴趣的可以点进去看一看。

对于Nginx，由于其发展迅速、性能卓越、开源开放，收割了很多Web服务提供与负载均衡、反向代理场景的市场，也衍生了很优秀的二次开发版本例如国人开发的OpenResty、阿里开源的Tengine等。在“在CentOS 8上使用Nginx 1.18”系列后面将择机对两个优秀的二次开发进行介绍。

## 在CentOS 8进行安装Nginx 1.18

虽然我们可以通过`yum -y install nginx`进行安装，但是在“源产库”系列第一篇文章《CentOS 8之初相识》中有过介绍，其镜像源预编译的版本为1.14，而截至文章发表之日Nginx的稳定版本已更新到了1.18，主线版本更新到了1.19，因此我们使用官网的稳定源码版本进行下载编译。

![-w1036](media/15941166309027/15941181736377.jpg)

> Nginx版本下载页，截至发文（2020-07-07）稳定版本已更新到了1.18，主线版本更新到了1.19

<!-- -->

> 小知识：关于稳定版本和主线版本。前者是Nginx更新接收针对高严重性错误的修复，但不会使用最新的功能，其版本号的第二位用偶数表示。而后者是Nginx是更新活跃的开发分支，其添加了最新功能和错误修复，其版本号的第二位用奇数表示。不过在Nginx中，“稳定”指的是功能和更新频率，它与软件质量无关。稳定分支在其生命周期中从不接收新功能，并且通常仅接收一个或两个更新，用于修复严重的错误。 稳定分支的生命周期一般是一年，每年四月官方就会停止对当前稳定分支的维护，不再提供错误修复补丁。

下载并解压`nginx-1.18.0.tar.gz`：

```shell
wget http://nginx.org/download/nginx-1.18.0.tar.gz;
tar -zxvf nginx-1.18.0.tar.gz;
```

进入目录`cd nginx-1.18.0`，目录结构如下：

```shell
总用量 1204
drwxr-xr-x 6 1001 1001    326 7月   7 18:50 auto
-rw-r--r-- 1 1001 1001 302863 4月  21 22:09 CHANGES
-rw-r--r-- 1 1001 1001 462213 4月  21 22:09 CHANGES.ru
drwxr-xr-x 2 1001 1001    168 7月   7 18:50 conf
-rwxr-xr-x 1 1001 1001   2502 4月  21 22:09 configure
drwxr-xr-x 4 1001 1001     72 7月   7 18:50 contrib
drwxr-xr-x 2 1001 1001     40 7月   7 18:50 html
-rw-r--r-- 1 1001 1001   1397 4月  21 22:09 LICENSE
drwxr-xr-x 2 1001 1001     21 7月   7 18:50 man
-rw-r--r-- 1 1001 1001     49 4月  21 22:09 README
drwxr-xr-x 9 1001 1001     91 7月   7 18:50 src
```

`conf`文件夹内为Nginx的初始配置文件，`contrib`文件夹放置了三位开源贡献者贡献的三个插件内容，`html`文件夹为默认站点文件内容，`src`文件夹为Nginx源码。`configure`文件为编译的配置文件。

拷贝Nginx安装包内如下文件到路径，可以让vim对`nginx.conf`的语言语法进行高亮解析：

```shell
cp -r contrib/vim/* ~/.vim/;
```

`./configure --help`可以查看Nginx编译支持参数列表，`configure`文件进行设置后，会在`objs`文件内生成Nginx的安装所需文件，其中`ngx_modules.c`，该文件决定接下来编译有哪些模块需要编译进Nginx。

本文不涉及模块的编译使用，我们使用最简单的编译设置进行编译安装：

```shell
./configure --prefix=/usr/local/nginx;
```

如果报如下错误，请执行命令`yum -y install pcre-devel openssl openssl-devel`进行安装：

```shell
...
checking for PCRE library ... not found
checking for PCRE library in /usr/local/ ... not found
checking for PCRE library in /usr/include/pcre/ ... not found
checking for PCRE library in /usr/pkg/ ... not found
checking for PCRE library in /opt/local/ ... not found

./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.
```

出现以下内容，即为`configure`文件设置完成：

```shell
Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + using system zlib library

  nginx path prefix: "/usr/local/nginx/"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"
```

紧接着执行`make`命令，执行后，在`objs`文件夹下可以看到编译后的`nginx`二进制文件和目标文件。无报错说明正常。如若首次安装Nginx，紧接着执行`make install`安装即可。如果是进行Nginx升级，`make install`是不应该用的，需要做的是将该目录下生成的`nginx`二进制文件拷贝到已有Nginx的二进制文件相应目录中。

## 在CentOS 8初步使用Nginx 1.18

安装完成，输入如下命令进行启动Nginx：

```shell
/usr/local/nginx/sbin/nginx;
```

Nginx基本指令格式为`nginx -s reload`，具体指令解释如下：

* `nginx -?/-h`为显示帮助信息；
* `nginx  -c`为使用指定的配置文件，后跟配置文件路径；
* `nginx -g`为指定配置指令，后跟需要指定的配置指令；
* `nginx-p`为指定运行目录，后跟运行目录路径；
* `nginx -s`发送信号，其中后跟参数`stop`为立即停止服务、`quit`为有序停止服务；`reload`为重载配置文件、`reopen`为重新开始记录日志文件；
* `nginx -t/-T`测试配置文件是否有语法错误；
* `nginx -v、nginx -V`打印Nginx的版本信息或编译信息。

在浏览器访问IP，如图，可以访问即正常。

![屏幕截图 2020-07-07 19.25.48](media/15941166309027/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202020-07-07%2019.25.48.png)

`ps -ef | grep nginx`查看进程情况：

```shell
root      8556     1  0 19:24 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody    8557  8556  0 19:24 ?        00:00:00 nginx: worker process
root      8561  8702  0 19:25 pts/0    00:00:00 grep --color=auto nginx
```

现在安装好的基本Nginx，完整的`nginx.conf`文件如下：

```conf
#user  nobody;
worker_processes  auto;

error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    server {
        listen       80;
        server_name  localhost;

        access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
```

Nginx配置语法有如下的规则：

1. 日志文件由指令与指令块构成；
2. 每条指令以`;`结尾，指令与参数间以空格符号分隔；
3. 指令块以`{}`将多条指令组织在一起；
4. `include`语句允许组合多个配置文件以提升可维护性；
5. 使用`#`添加注释，提高可读性；
6. 使用`$`可调用变量；
7. 部分指令的参数支持正则表达式。

Nginx有多种指令块，其中`http`块表示此为HTTP协议处理块、`upstream`表示有上游服务提供的配置信息、`location`对应URL的表达式、`server`对应一个或一组域/域名的访问。

以下是配置文件部分的参数解释:

* `worker_processes`为设定工作进程数，若设置为`auto`则Nginx将根据机器的内核数进行设定分配，如无特殊需求一般建议设置为`auto`。
* `error_log`设定错误日志的路径与等级，其中等级有`debug`, `info`, `notice`, `warn`, `error`, `crit`, `alert`, `emerg`几种，以严重性从高到低的顺序列出。根据官方文档的解释，设定某个级别的意义是该级别及以上的日志会被打印在日志文件中，例如设置`info`则包括其本身在内以及`notice`, `warn`, `error`, `crit`, `alert`, `emerg`都会被列出。若第二个字段为空，默认为`error`。
* `log_format main 'XXX'`设定日志格式，`main`标示为命名，在遇到对不同域名进行不同格式的命名记录时需要用到，`server`区块下`access_log logs/access.log main;`可以以main格式进行记录。

关于其他参数例如`pid`、`worker_connections`等，以及`server`、`upstream`、`location`指令块，将在后续的“在CentOS 8上使用Nginx 1.18”系列文章中陆续介绍与展示使用方法。

## 参考资料

1. [nginx 主线版 1.17.0 发布，1.14 稳定分支已停止维护](oschina.net/news/106928/nginx-1-16-1-17-released)
2. [Index - nginx.org](nginx.org)
3. [Core functionality - nginx.org](http://nginx.org/en/docs/ngx_core_module.html#error_log)
