CentOS7 / Debian10 使用源码包编译安装 Nginx
> 本教程需要掌握 `Linux` 下 `vim 编辑工具` 的使用方法,以及 `ftp` 上传文件的方法 # 下载 Nginx下载地址:[http://nginx.org/en/download.html](http://nginx.org/en/download.html) 下载`Stable version`版  > 注: - `Mainline version` :主线版 - 包括最新功能和错误修复,并始终是最新的。它是可靠的,但它可能包括一些实验模块,它也可能有一些新的bug - `Stable version` :稳定版 - 不包括所有最新功能,但具有关键错误修复,始终向后移植到主线版本。我们建议生产服务器的稳定版本 下载完成后,使用ftp工具上传工具将安装包上传到`/root`目录下 > 也可以使用右击复制下载地址,使用 `wget` 命令直接下载到系统中 > 注:以下命令使用root账户 # 安装依赖 ```bash # CentOS7 yum -y install gcc-c++ pcre-devel zlib-devel openssl-devel # Debian10 apt-get install gcc libpcre3-dev libssl-dev libzip-dev make ``` # 解压 ```bash tar -zxf nginx-1.22.0.tar.gz cd nginx-1.22.0/ ``` # 编译 配置安装选项: - `--prefix` :设置安装目录(默认为 `/usr/local/nginx`) - `--user` :设置为 `root` 用户 - `--with-http_ssl_module` :设置支持 `https` 协议 - `--with-http_v2_module` :支持 `HTTP/2` 协议 - `--with-http_sub_module` :支持字符串替换 ```bash ./configure --prefix=/usr/local/nginx --user=root --with-http_ssl_module --with-http_v2_module --with-http_sub_module ``` 编译、安装 ```bash make make install ``` # 删除源码包 ```bash # 返回上级目录 cd .. # 删除压缩包 rm -rf nginx-1.22.0.tar.gz # 删除解压后的文件(可以留着,方便后面加模块重新编译) rm -rf nginx-1.22.0 ``` # 添加环境变量 编辑环境变量配置文件 ```bash vim /etc/profile ``` 设置 `PATH` 值 ```bash export PATH=$PATH:/usr/local/nginx/sbin ``` 环境变量立即生效 ```bash source /etc/profile ``` # 添加为系统服务 新建服务文件 ```bash vim /usr/lib/systemd/system/nginx.service ``` 添加如下内容并保存 ``` [Unit] Description=nginx - high performance web server Documentation=http://nginx.org/en/docs/ After=network-online.target remote-fs.target nss-lookup.target Wants=network-online.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true [Install] WantedBy=multi-user.target ``` # 设置开机自启 ```bash # 开启开机自启 systemctl enable nginx.service # 关闭开机自启 systemctl disable nginx.service ``` # 启动与关闭 ``` # 启动 systemctl start nginx.service # 关闭 systemctl stop nginx.service # 查看状态 systemctl status nginx.service ``` # Nginx基本操作 ## 检查配置文件 ```bash nginx -t ``` ## 操作进程 ```bash nginx -s <SIGNAL> ``` `<SIGNAL>`可以是以下之一: - `quit` :优雅地关闭 - `reload` :重新加载配置文件 - `reopen` :重新打开日志文件 - `stop` :立即关机(快速关机) # 附:Nginx官方编译参数说明 链接:[http://nginx.org/en/docs/configure.html](http://nginx.org/en/docs/configure.html) # 附:Nginx实现反向代理 ```conf server { listen 80; server_name domain.com; # 你的网址名称(非必填) # 请求头相关设置 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; # 所有以/开头的请求 location / { # 转发后端地址 proxy_pass http://127.0.0.1:8080/; proxy_redirect default; } } ```