Nginx设置HTTPS默认站点

on May 25th, 2022 by 小桥 | No Comments »

Nginx不设置HTTPS默认站点的话,用户通过ip访问443端口可以从服务器返回的证书信息来知道服务器上面跑的HTTPS网站是什么。我们可以通过配置HTTPS默认站点来避免这个问题。

首先,生成一个自签名的证书:

openssl genrsa -out hostname-key.pem 2048
openssl req -new -key hostname-key.pem -out hostname-request.csr
openssl x509 -req -extensions v3_req -days 3650 -in hostname-request.csr -signkey hostname-key.pem -out hostname-cert.pem
或者
openssl req -x509 -newkey rsa:2048 -sha256 -days 3650 -nodes -keyout hostname.key -out hostname.crt -subj '/CN=notexist.com' -addext 'subjectAltName=DNS:notexist.com,DNS:www.notexist.com'

然后把hostname-key.pem、hostname-cert.pem复制到/etc/nginx,并修改Nginx的配置文件,添加配置。

server {
        server_name _;
        listen 443 ssl http2;

        ssl_certificate  /etc/nginx/hostname-cert.pem;
        ssl_certificate_key /etc/nginx/hostname-key.pem;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-CHACHA20-POLY1305;
        ssl_prefer_server_ciphers on;
        return 503;
}

此时再尝试使用IP访问443端口,证书是自签名证书,服务器返回的也是503错误,符合预期。

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA * Time limit is exhausted. Please reload the CAPTCHA.