nginx配置自签名https证书+basic auth验证

1.生成自签名https证书

参考

1.1生成证书的脚本

# vi gencert.sh
#!/bin/sh

# create self-signed server certificate:

read -p "Enter your domain [www.example.com]: " DOMAIN

echo "Create server key..."

#openssl genrsa -des3 -out $DOMAIN.key 1024
openssl genrsa -des3 -out $DOMAIN.key 2048

echo "Create server certificate signing request..."

SUBJECT="/C=US/ST=Mars/L=iTranswarp/O=iTranswarp/OU=iTranswarp/CN=$DOMAIN"

openssl req -new -subj $SUBJECT -key $DOMAIN.key -out $DOMAIN.csr

echo "Remove password..."

mv $DOMAIN.key $DOMAIN.origin.key
openssl rsa -in $DOMAIN.origin.key -out $DOMAIN.key

echo "Sign SSL certificate..."

openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt

echo "TODO:"
echo "Copy $DOMAIN.crt to /etc/nginx/ssl/$DOMAIN.crt"
echo "Copy $DOMAIN.key to /etc/nginx/ssl/$DOMAIN.key"
echo "Add configuration in nginx:"
echo "server {"
echo "    ..."
echo "    listen 443 ssl;"
echo "    ssl on;"
echo "    ssl_certificate     /etc/nginx/ssl/$DOMAIN.crt;"
echo "    ssl_certificate_key /etc/nginx/ssl/$DOMAIN.key;"
echo "}"

1.2生成证书

./gencert.sh
Enter your domain [www.example.com]: sub.domain.com
Create server key...
Generating RSA private key, 2048 bit long modulus
..........................+++
.....................+++
e is 65537 (0x10001)
Enter pass phrase for sub.domain.com.key:
Verifying - Enter pass phrase for sub.domain.com.key:
Create server certificate signing request...
Enter pass phrase for sub.domain.com.key:
Remove password...
Enter pass phrase for sub.domain.com.origin.key:
writing RSA key
Sign SSL certificate...
Signature ok
....

1.3copy证书到相应位置nginx/conf/cert目录下

2.nginx支持https证书

# vi sub.domain.com.conf
server{
    charset utf-8;

    listen 80;
    listen 443 ssl;
    ssl on;
    ssl_certificate /usr/local/nginx/conf/cert/sub.domain.com.crt;
    ssl_certificate_key /usr/local/nginx/conf/cert/sub.domain.com.key;
    server_name sub.domain.com;

    access_log  /home/wwwlogs/sub.domain.com.log;
    error_log /home/wwwlogs/sub.domain.com.err;

    location / {
        proxy_pass http://127.0.0.1:99999;
    }
}

3.生成basicauth用的密码文件

参考

yum install httpd-tools -y
# magina是用户名,要求输入两次密码
htpasswd -c -d /usr/local/nginx/conf/pass_file magina
New password: 
Re-type new password:

4.配置nginx支持basicauth

# vi sub.domain.com.conf
server{
    charset utf-8;

    listen 80;
    listen 443 ssl;
    ssl on;
    ssl_certificate /usr/local/nginx/conf/cert/sub.domain.com.crt;
    ssl_certificate_key /usr/local/nginx/conf/cert/sub.domain.com.key;
    server_name sub.domain.com;

    # 以下2行支持 basic auth
    auth_basic "sub auth";
    auth_basic_user_file /usr/local/nginx/conf/pass_file;

    access_log  /home/wwwlogs/sub.domain.com.log;
    error_log /home/wwwlogs/sub.domain.com.err;

    location / {
        proxy_pass http://127.0.0.1:99999;
    }
}

相关推荐