环境
Centos7.6nginx-1.17.0
下载
官网:http://nginx.org/download/nginx-1.17.0.tar.gz
环境确认
在安装nginx前首先要确认系统中是否安装gcc、pcre-devel、zlib-devel、openssl-devel
- 检查是否安装过软件包
yum list installed | grep xxx
- 安装软件包
yum -y install gcc pcre-devel zlib-devel openssl openssl-devel
上图为已安装
安装
- 将nginx-1.17.0.tar.gz上传至服务器并解压
tar -xzvf nginx-1.17.0.tar.gz
解压后如下所示:
- nginx目录下编译安装nginx
./configure --prefix=/usr/local/nginx1.17.0 --conf-path=/usr/local/nginx1.17.0/nginx.conf --with-http_stub_status_module --with-http_ssl_module
--with-http_ssl_module配置nginx支持https协议访问,不使用https可以不用添加该命令
该命令编译nginx时将配置文件nginx.conf生成在nginx目录下,因编译后出现错误,采用这种方式,详见后面错误记录,因此,nginx的配置文件不再是conf中的nginx.conf
- 顺序执行make,make install编译
make
make install
- 测试是否安装成功
./sbin/nginx -t
- 启动nginx
./sbin/nginx
- 停止nginx
./sbin/nginx -s stop
- 重启nginx
./sbin/nginx -s reload
- 查看nginx进程
ps -ef | grep nginx
- 访问:浏览器访问服务器IP(nginx默认端口为80),出现如下界面则证明成功
配置HTTPS
- 服务器上安装openssl,openssl-devel
yum install openssl openssl-devel
- 创建证书存放目录
mkdir /usr/local/nginx/conf/ssl
- 创建服务器私钥
openssl genrsa -des3 -out server.key 2048 #根据提示输入证书口令
- 创建签名请求的证书(CSR)
openssl req -new -key server.key -out server.csr #输入上面设置的口令,根据提示输入相应的信息
- 对key进行解密
openssl rsa -in server.key -out server_nopasswd.key
- 标记证书使用上述私钥和CSR
openssl x509 -req -days 365 -in server.csr -signkey server_nopasswd.key -out server.crt
- vim修改nginx配置文件,加载ssl证书
server { listen 443 ssl; server_name localhost; ssl_certificate /usr/local/nginx-1.17.0/conf/ssl/server.crt; ssl_certificate_key /usr/local/nginx-1.17.0/conf/ssl/server.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_protocols TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root html; index index.html index.htm; } }
- 输入证书密码启动nginx
- 浏览器访问测试:https://服务器IP + 端口443,出现如下界面则成功
错误记录
- nginx报错:cp: `conf/koi-win' and `/usr/local/nginx/conf/koi-win' are the same file
该错误为编译安装nginx时没有指定conf-path出现的,出现问题的命令:
./configure --prefix=/usr/local/nginx1.17.0 --with-http_stub_status_module --with-http_ssl_module
将命令改为如下指定conf-path后正常:
./configure --prefix=/usr/local/nginx1.17.0 --conf-path=/usr/local/nginx1.17.0/nginx.conf --with-http_stub_status_module --with-http_ssl_module