为Nginx配置SSL证书
安装Nginx的http_ssl_module模块
./configure --prefix=/usr/local/nginx --with-http_ssl_module
#编译安装nginx时,需要使用--with-http_ssl_module参数。使用openssl签发证书
生成RSA私钥
openssl genrsa -des3 -out server.key 2048
#生成私钥后还要设置一个私钥密码。生成CSR(证书签名请求)
openssl req -new -key server.key -out server.csr
#依次提示输入国家、地区,城市,组织,组织单位、Common Name、电子邮箱地址。Common Name为网站的域名。删除私钥密码
openssl rsa -in server.key -out server.key
#删除密码方便nginx使用。生成自签名证书
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
#证书有效期为365天生成pem格式公钥
openssl x509 -in server.crt -out server.pem -outform PEM在Nginx中启用SSL
存放证书文件
mkdir /usr/local/nginx/conf/cert
在Nginx的conf目录内建立cert目录,用于存放证书文件,同时方便在Nginx配置文件中,使用相对地址进行证书读取。修改Nginx主机配置文件
server {
listen 443 ssl; #SSL协议访问端口号为443。此处如未添加ssl,可能会造成Nginx无法启动。
server_name ywngo.com; #将localhost修改为您证书绑定的域名,例如:www.example.com。
root html;
index index.php index.html index.htm;
ssl_certificate cert/domain name.pem; #将domain name.pem替换成您证书的文件名。
ssl_certificate_key cert/domain name.key; #将domain 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 TLSv1.1 TLSv1.2;#使用该协议进行配置。
ssl_prefer_server_ciphers on;
location / {
root html;#站点目录。
index index.php index.html index.htm;
}
}设置HTTP请求自动跳转HTTPS
server {
listen 80;
server_name localhost; #将localhost修改为您证书绑定的域名,例如:www.example.com。
rewrite ^(.*)$ https://$host$1 permanent; #将所有http请求通过rewrite重定向到https。
location / {
index index.html index.htm;
}
}完成后重启Nginx,并访问网站进行测试。