本文讲述 Linux 系统中如何从源码安装 Nginx。

从 Nginx 官方文档了解到,安装 Nginx 需要有以下必须的模块:

  • openssl,用于加解密数据
  • pcre,用于正则表达式匹配
  • zlib,用于加解压缩数据

模块对应官网

下载并解压必须的文件:

1
2
3
4
5
6
7
8
$ wget https://nginx.org/download/nginx-1.18.0.tar.gz
$ wget https://www.openssl.org/source/openssl-1.1.1g.tar.gz
$ wget https://ftp.pcre.org/pub/pcre/pcre-8.44.zip
$ wget https://zlib.net/zlib-1.2.11.tar.gz
$ tar -zxvf nginx-1.18.0.tar.gz
$ tar -zxvf openssl-1.1.1g.tar.gz
$ unzip pcre-8.44.zip
$ tar -zxvf zlib-1.2.11.tar.gz

所有文件都准备好了,可以进行安装前的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ cd nginx-1.18.0
$ ./configure --with-http_ssl_module --with-openssl=../openssl-1.1.1g --with-zlib=../zlib-1.2.11 --with-pcre=../pcre-8.44

······
Configuration summary
+ using PCRE library: ../pcre-8.44
+ using OpenSSL library: ../openssl-1.1.1g
+ using zlib library: ../zlib-1.2.11

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"

如无意外,控制台的输出将会如上。

可以发现目录中生成了 Makefile,使用 make 进行编译安装:

1
$ make && sudo make install

Nginx 安装在了 /usr/local/nginx/sbin/nginx 目录中,使用软链进行指向:

1
$ sudo ln -s /usr/local/bin/nginx /usr/local/nginx/sbin/nginx

测试:

1
2
3
$ sudo nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

加入 Nginx 模块

Nginx 允许开发第三方模块。比如 nginx-upload-module 就是一个用于解析上传文件的 Nginx 模块。

如果要安装它,需要重新编译 Nginx:

1
2
3
$ git clone https://github.com/vkholodkov/nginx-upload-module.git
$ cd nginx-1.18.0
$ ./configure --with-http_ssl_module --with-openssl=../openssl-1.1.1g --with-zlib=../zlib-1.2.11 --with-pcre=../pcre-8.44 --add-module=../nginx-upload-module

注意后面增加了 --add-module 参数,并传入了 nginx-upload-module 的路径。

重新编译:

1
2
$ make
$ sudo make install

参考