首页 > nginx > nginx禁止未绑定https域名访问

nginx禁止未绑定https域名访问

2020年2月19日 发表评论 阅读评论

http的情况系下,我们使用如下办法禁止未授权的域名指向我们的服务器

 server {
    listen       80  default_server;
    server_name  _;
    return       444;
} 

如何把端口简单改成443,会宝如下错误

[root@VM_0_16_centos conf]# nginx -t
 nginx: [emerg] no "ssl_certificate" is defined for the "listen … ssl" directive in /usr/local/nginx/conf/nginx.conf:105
 nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

在我们未设置默认server的情况下,nginx会匹配配置中的第一个server来响应非自己绑定的域名。

这种情况下需要自己自定义一个签名证书来解决这个问题。

1.nginx的配置修改改为

server {
     listen 443 ssl;
     server_name _;
     ssl_certificate /usr/local/nginx/conf/ssl/default.crt;
     ssl_certificate_key /usr/local/nginx/conf/ssl/default.key;
     return       444;
 }

2.创建自定义的key

[root@VM_0_16_centos conf]# sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /usr/local/nginx/conf/ssl/default.key -out /usr/local/nginx/conf/ssl/default.crt
 Generating a 2048 bit RSA private key
 ………………………………………..+++
 ……………………+++
 writing new private key to '/usr/local/nginx/conf/ssl/default.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) []:beijing
 Locality Name (eg, city) [Default City]:beijing
 Organization Name (eg, company) [Default Company Ltd]:default
 Organizational Unit Name (eg, section) []:default
 Common Name (eg, your name or your server's hostname) []:default
 Email Address []:default

3.重新加载配置

[root@VM_0_16_centos conf]# nginx -t
 nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
 nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
 [root@VM_0_16_centos conf]# nginx -s reload

80 443合并的例子

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name _;

    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_session_tickets off;

    return 404;
}

 

分类: nginx 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.