使用nginx配置https代理分为两种,一种是后端为http应用时前端代理使用ssl证书配置https的反向代理,另一种是后端为https应用,前端仅做反向代理,本文阐述第一种方案的配置方法。
环境:
OS:RHEL 6.5
NGINX:nginx-1.10.2
一、使用openssl配置ssl证书
1、生成服务器端的私钥(key文件)
[root@app2 ssl]# openssl genrsa -des3 -out server.key 2048
Generating RSA private key, 2048 bit long modulus
..............................................................+++
.......................................................+++
e is 65537 (0x10001)
Enter pass phrase for server.key:bing123
Verifying - Enter pass phrase for server.key:bing123
[root@app2 ssl]# ls
server.key
运行时会提示输入密码,此密码用于加密key文件(参数des3便是指加密算法,当然也可以选用其他你认为安全的算法.),以后每当需读取此文件(通过openssl提供的命令或API)都需输入口令.如果觉得不方便,也可以去除这个口令,但一定要采取其他的保护措施!
去除key文件口令的命令:
openssl rsa -in server.key -out server2.key (将生成一个新的key文件,使用该文件不需要密码,我们在后面的使用过程中可以将server2.key改为名server.key,而原server.key另重命名保存)
2、生成Certificate Signing Request(CSR),生成的csr文件交给CA签名后形成服务端自己的证书.
[root@app2 ssl]# openssl req -new -key server.key -out server.crs
Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:china
Locality Name (eg, city) [Default City]:changsha
Organization Name (eg, company) [Default Company Ltd]:czhy Ltd
Organizational Unit Name (eg, section) []:czhy
Common Name (eg, your name or your server's hostname) []:czhy
Email Address []:xxx@qq.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:bing123
An optional company name []:xxx@qq.com
[root@app2 ssl]# ls
server.crs server.key
[root@app2 ssl]#
3、自签名的方式签发我们之前的申请的证书,生成的证书为ca.crt
[root@app2 ssl]# openssl x509 -req -days 3650 -in /ssl/server.crs -signkey /ssl/server.key -out /ssl/ca.crt
Signature ok
subject=/C=cn/ST=china/L=changsha/O=czhy Ltd/OU=czhy/CN=czhy/emailAddress=xxx@qq.com
Getting Private key
Enter pass phrase for /ssl/server.key:
[root@app2 ssl]# ls
ca.crt server.crs server.key
二、nginx的https配置
1、http_ssl_module模块
当时由于安装nginx时,未编译http_ssl_module模块,导致nginx重启失败------提示:nginx: [emerg] the "ssl" parameter requires ngx_http_ssl_module in /usr/local/nginx/···
所以需要重新编译nginx来添加需要的模块。
cd /soft/nginx-1.10.2
./configure --prefix=/usr/local/nginx --with-http_ssl_module
make
/soft/nginx-1.10.2/objs目录下就多了个nginx
将该nginx替换到/usr/local/nginx/sbin/下
重启nginx服务
2、https配置
例如下面的配置实现的效果https://192.168.184.221
修改nginx.conf文件
server {
listen 443 ssl;
server_name httsserver;
ssl on;
ssl_certificate /ssl/ca.crt;
ssl_certificate_key /ssl/server.key; #若使用含密码的key文件则在启动或关闭nginx时需要输入创建key文件时使用的密码
location / {
proxy_pass http://192.168.184.221:8080;
root html;
index index.html index.htm;
}
}