Centos环境下安装配置Nginx并开启HTTPS服务
一、环境准备
Centos7.6 64位服务器(阿里云)一台
nginx-1.15.12
SSL证书(阿里云云盾证书服务(包年)
Xsell、Notepad++等工具
二、环境搭建
-
将下载好的nginx-1.15.12.tar.gz上传到服务器解压
-
cd 命令进入到解压后的Nginx文件夹
-
安装相关依赖
1.安装gcc gcc-c++(如新环境,未安装请先安装) yum install -y gcc gcc-c++ 2.安装重定向支持 yum -y install pcre-devel 3.开启SSL支持 yum -y install openssl openssl-devel 4.Nginx安装设置(设置安装位置),开启SSL支持(否则的话开启https的时候会报Starting nginx: nginx: [emerg] unknown directive "ssl" in /usr/local/nginx/conf/nginx.conf:11错误) ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module 5.编译&&安装 make && make install 6.启动Nginx测试 cd /usr/local/nginx/sbin ./nginx 7.浏览器输入域名访问,出现Welcome to Nginx 即代表成功
三、开启HTTPS
- 将申请的阿里云SSL证书下载到本地(下载选择相应的web服务器,这里选择的是Nginx)
-
将下载后的证书解压有两个文件,重命名成个人域名的名称(个人习惯),上传至/usr/local/nginx/conf/ssl目录下。【根据个人情况修改】
-
编辑nginx.conf文件
server { listen 443 ssl; server_name localhost; ssl_certificate ./ssl/mywebapp.pem; ##根据自己的文件路径写 ssl_certificate_key ./ssl/mywebapp.key; ##根据自己的文件路径写 ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root html; index index.html index.htm; } }
添加80端口重定向到https 443端口
rewrite ^ https://$http_host$request_uri? permanent; ##老版本 return 301 https://【域名】$request_uri ; ##新版本
完整如下
server { listen 80; server_name localhost; rewrite ^ https://$http_host$request_uri? permanent; #charset koi8-r; #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; } }
-
检查配置文件是否有问题
进入到/usr/local/nginx/sbin目录下输入./nginx -t 检查
没有问题开启Nginx服务
-
5.浏览器输入域名查看是否是https访问
大功告成
Nginx常用命令
nginx -s quit 优雅停止nginx,有连接时会等连接请求完成再杀死worker进程
nginx -s reload 优雅重启,并重新载入配置文件nginx.conf
nginx -s reopen 重新打开日志文件,一般用于切割日志
nginx -v 查看版本
nginx -t 检查nginx的配置文件
nginx -h 查看帮助信息
nginx -V 详细版本信息,包括编译参数
nginx -c filename 指定配置文件