+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
张贺,多年互联网行业工作经验,担任过网络工程师、系统集成工程师、LINUX系统运维工程师
个人网站:www.zhanghehe.cn
笔者微信:zhanghe15069028807,现居济南历下区
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
nginx实现https
关于密码学的内容我在这里不过多阐述,这里面只上操作步骤,如果有兴趣的同学请参考我这一篇博文: https://www.cnblogs.com/yizhangheka/p/11038825.html
简单的理解,假如说A是CA,,B信任A,A给B颁发了一个证书,C也是如此,也获得一个CA颁发的证书;那么当B和C合作的时候,一方出示CA给的证书,另一方就能识别出来,并予以信任合作,其信任合作的前提是基于B和C对A的信任。
私有CA的IP | 192.168.80.5 |
---|---|
nginx的IP | 192.168.80.20 |
CA自签
-
生成自己的私钥
[root@n1 ~]# cd /etc/pki/CA/ [root@n1 CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048) [root@n1 CA]# touch index.txt [root@n1 CA]# echo 01 > serial
-
生成自己的证书
[root@n1 CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 7300 Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:bejing Locality Name (eg, city) [Default City]:bejing Organization Name (eg, company) [Default Company Ltd]:bejing Organizational Unit Name (eg, section) []:ops Common Name (eg, your name or your server\'s hostname) []:ca.magedu.com Email Address []:caadmin@magedu.com
nginx生成签署请求
-
生成自己的私钥和密钥签署文件
[root@Web ~]# cd /etc/nginx/ [root@Web nginx]# clear [root@Web nginx]# pwd /etc/nginx [root@Web nginx]# openssl req -new -key nginx.key -out nginx.csr Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:bejing Locality Name (eg, city) [Default City]:bejing Organization Name (eg, company) [Default Company Ltd]:bejing Organizational Unit Name (eg, section) []:ops Common Name (eg, your name or your server\'s hostname) []:www.zhanghe.com Email Address []:746620446@qq.com Please enter the following \'extra\' attributes to be sent with your certificate request A challenge password []: An optional company name []:
-
将密钥签署文件发送到CA上
[root@Web nginx]# scp nginx.csr root@192.168.80.5:/root
CA签名
-
在私有CA上对nginx网站生成的签署请求进行签名,并生成了一个签署好的证书文件: www.zhanghe.com.crt
openssl ca -in nginx.csr -out www.zhanghe.com.crt -days 365
-
将证书送给nginx服务器的/etc/nginx
scp www.zhanghe.com.crt root@192.168.80.20:/etc/nginx
Nginx导入证书
[root@Web ~]# yum -y install mod_ssl
vim /etc/nginx/nginx.conf
server {
listen 443 ssl;
root /usr/share/nginx/html;
include /etc/nginx/default.d/*.conf;
server_name www.zhangge.com;
ssl on;
ssl_certificate /etc/nginx/www.zhanghe.com.crt;
ssl_certificate_key /etc/nginx/nginx.key;
ssl_session_cache shared:sslcache:20m;
}
客户端验证
在验证之要添加hosts记录,在访问的时候必须通过域名访问
curl --cacert cacert.pem https://www.zhanghe.com
访问80时自动跳转到443
分享nginx下http访问自动跳转到https上,即nginx 80端口重定向到443端口。配置如下:
按照如下格式修改nginx.conf 配置文件,80端口会自动转给443端口,这样就强制使用SSL证书加密了。访问http的时候会自动跳转到https上面。
server {
listen 80;
server_name www.域名.com;
rewrite ^(.*) https://$server_name$1 permanent;
}
server {
listen 443;
server_name www.域名.com;
root /home/www;
ssl on;
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
}
修改配置文件后,重启nginx。