Linu安装Nginx+升级到https

88 阅读2分钟

1、Nginx安装

#gcc安装,nginx源码编译需要
yum install gcc-c++

#PCRE pcre-devel 安装,nginx 的 http 模块使用 pcre 来解析正则表达式
yum install -y pcre pcre-devel

#zlib安装,nginx 使用zlib对http包的内容进行gzip
yum install -y zlib zlib-devel

#OpenSSL 安装,强大的安全套接字层密码库,nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http)
yum install -y openssl openssl-devel

#下载版本号可根据目前官网最新稳定版自行调整
wget -c https://nginx.org/download/nginx-1.16.1.tar.gz

#根目录使用ls命令可以看到下载的nginx压缩包,然后解压
tar -zxvf nginx-1.16.1.tar.gz

#解压后进入目录
cd nginx-1.16.1

#使用默认配置

./configure --prefix=/usr/local/nginx --with-http_ssl_module

#编译安装
make
make install

#查找安装路径,默认都是这个路径
[root@VM_0_12_centos ~]# whereis nginx
nginx: /usr/local/nginx

#启动、停止nginx
cd /usr/local/nginx/sbin/
./nginx     #启动
./nginx -s stop  #停止,直接查找nginx进程id再使用kill命令强制杀掉进程
./nginx -s quit  #退出停止,等待nginx进程处理完任务再进行停止
./nginx -s reload  #重新加载配置文件,修改nginx.conf后使用该命令,新配置即可生效

#重启nginx,建议先停止,再启动
./nginx -s stop
./nginx

2、申请https

  1. 申请SSL证书地址
  2. 创建证书创建证书
  3. 下载证书image.png
  4. 在/usr/local/nginx/conf/目录下创建cert文件
  5. 将证书上传到/usr/local/nginx/conf/cert文件夹下

3、服务器部署https

  • 配置server
#以下属性中,以ssl开头的属性表示与证书配置有关。
server {
    listen 443 ssl;
    server_name yourdomain;
    root html;
    index index.html index.htm;
    ssl_certificate cert/cert-file-name.pem;  
    ssl_certificate_key cert/cert-file-name.key; 
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; 
    ssl_prefer_server_ciphers on;
    location / {
        root html;  
        index index.html index.htm;
    }
}
  • 配置http请求重定向到https
server {
    listen 80;
    server_name your service name; #需要将域名替换成证书绑定的域名。
    rewrite ^(.*)$ https://$host$1; #将所有HTTP请求通过rewrite指令重定向到HTTPS。
    location / {
        index index.html index.htm;
    }
}

4、重启nginx服务

cd /usr/local/nginx/sbin
./nginx -s stop
./nginx