创建认证文件和公有密钥的文件夹

创建存放的文件夹

sudo mkdir /etc/nginx/ssl
cd /etc/nginx/ssl

创建Server Key and Certificate Signing Request

sudo openssl genrsa -des3 -out server.key 1024
sudo openssl req -new -key server.key -out server.csr

移除密码

如果server.key有密码,每次重启的时候都得手动输入密码, 所以要去掉

sudo cp server.key server.key.org
sudo openssl rsa -in server.key.org -out server.key

对SSL Certificate签名

sudo openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt

配置Certificate

添加以下内容

server {
        listen 443;
        server_name example.com;

        root /usr/share/nginx/www;
        index index.html index.htm;

        ssl on;
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key; 
}

启动

sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/example
sudo service nginx restart

客户端使用ssl认证

USER_NAME=$1
mkdir ./$USER_NAME
cd ./$USER_NAME
openssl genrsa -des3 -out $USER_NAME.key 1024
openssl req -new -key $USER_NAME.key -out $USER_NAME.csr
openssl x509 -req -days 365 -in $USER_NAME.csr -CA server.crt -CAkey server.key -set_serial 01 -out $USER_NAME.crt
openssl pkcs12 -export -clcerts -in $USER_NAME.crt -inkey $USER_NAME.key -out $USER_NAME.p12

修改nginx.conf

ssl_client_certificate /etc/nginx/ssl/server.crt;
ssl_verify_client on;
ssl_verify_depth 1;