本文记录了nginx怎么配置ssl证书的整个流程,希望能够帮到大家。
一、使用openssl生成证书
-
openssl是目前最流行的SSL密码库工具,其提供了一个通用、健壮、功能完备的工具套件,用以支持SSL/TLS协议的实现
openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /usr/local/ssl/nginx.key -out /usr/local/ssl/nginx.crt
# openssl req生成证书
# -x509 输出 x509 结构而不是证书。
# -nodes 不加密输出密钥
# -days -x509 生成的证书的有效天数。
# -newkey rsa:2048 生成大小为"位"的新 RSA 密钥
# -keyout 要将密钥发送到的文件
# -out 输出文件
[root@localhost ~]# openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /usr/local/ssl/nginx.key -out /usr/local/ssl/nginx.crt
Generating a 2048 bit RSA private key
....+++
.........+++
writing new private key to '/usr/local/ssl/nginx.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) []:HN
Locality Name (eg, city) [Default City]:Zheng Zhou
Organization Name (eg, company) [Default Company Ltd]:.
Organizational Unit Name (eg, section) []:.
Common Name (eg, your name or your server's hostname) []:www.test.com
Email Address []:.
二、nginx配置
server {
listen 443 ssl;
server_name www.test.com;
ssl_certificate /usr/local/ssl/nginx.crt;
ssl_certificate_key /usr/local/ssl/nginx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
#禁止在header中出现服务器版本,防止黑客利用版本漏洞攻击
server_tokens off;
#如果是全站 HTTPS 并且不考虑 HTTP 的话,可以加入 HSTS 告诉你的浏览器本网站全站加密,并且强制用 HTTPS 访问
fastcgi_param HTTPS on;
fastcgi_param HTTP_SCHEME https;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
server {
listen 80;
server_name www.test.com;
rewrite ^/(.*)$ https://www.test.com/$1 permanent;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}