天天看点

windows下nginx配置OpenSSL自签名证书

版本

nginx:1.16.1

安装git

windos下可以安装git工具后,自带openssl工具。

生成证书的申请文件和私钥文件

openssl  req -nodes -newkey rsa:1024 -out myreq.pem -keyout privatekey.pem
# req:request的简写,代表发出一个申请数字证书的请求
# -nodes:不生成pin码,简化流程
# -newkey:生成新证书并指明加密算法和长度,也可以写成2048
# -out:输出一个请求文件,非密码文件
# -keyout:生成私钥
           

生成证书

使用申请文件和私钥进行证书的申请,自己给自己颁发证书。

openssl req -in myreq.pem -x509 -key privatekey.pem -out mycert.pem -days 365
# -in:用之前的申请文件作为输入
# -x509:证书格式
# -key:私钥文件
# -out:产出的证书文件
# -days:证书有效期
           

配置nginx

将上面生成的文件放到

nginx/conf/cert

目录下,目录结构:

└─conf
    │  nginx.conf
    └─cert
            mycert.pem
            myreq.pem
            privatekey.pem
            使用openssl生成实现https.sh
           

完整的nginx配置文件如下:

#user  nobody;
worker_processes  1;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    
    # 配置服务器集群组
	upstream backend_server{
		# 1
		server 127.0.0.1:8080 weight=1 max_fails=2 fail_timeout=5s;
		keepalive 100;
	}
    
    server {
        listen       80;
        server_name  192.168.1.2;

        # 把http的域名请求转成https
        rewrite ^(.*)$ https://$host$1 permanent; 
        #rewrite ^/(.*) https://$server_name$request_uri redirect;
		
        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        
        location / {
            root   html;
            index  index.html index.htm;
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  192.168.1.2;
        keepalive_timeout  70;
        
        ssl_certificate      cert/mycert.pem;
        ssl_certificate_key  cert/privatekey.pem;

        ssl_session_cache    shared:SSL:10m;
        ssl_session_timeout  10m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;
       
        # 默认访问服务页面
        location = / {
           rewrite ^(.*)$ http://$host/server/ redirect; 
            #root   html;
            #index  index.html index.htm;
        }
		# 映射服务器集群
		location /server/{
            proxy_connect_timeout 5s;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            
			proxy_pass http://backend_server;            
		}
       
        
        location /status{
            stub_status on;
        }
    }
	# include vhost/*.conf;

}

           

继续阅读