Nginx配置-SSL&The plain HTTP request was sent to HTTPS port解决

Nginx配置-SSL

  • 准备ssl证书
  • 配置示例
  • 配置强制http访问也走https


准备ssl证书

可以直接从阿里云控制台申请免费证书(每年20个,每个有一年有效期)
也可以使用自签证书,Nginx解决通过openssl自签名证书访问Https报不安全告警的问题

配置示例

    upstream tomcatserver {
         server 127.0.0.1:8801 max_fails=3 fail_timeout=3s;
         server 127.0.0.1:8802 max_fails=3 fail_timeout=3s;         
    }
    
    server {
        listen       8888 ssl;
        server_name  localhost;
        
        ssl_certificate      /usr/local/nginx/ssl/nginx.pem;
        ssl_certificate_key  /usr/local/nginx/ssl/nginx.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            proxy_pass http://tomcatserver/;
            client_max_body_size  500m;
            proxy_connect_timeout 300;
            proxy_http_version 1.1;
            proxy_send_timeout 300;
            proxy_read_timeout 300;
            proxy_set_header    Host             $http_host;
            proxy_set_header    X-Real-IP        $remote_addr;
            proxy_set_header    X-Real-Port      $remote_port;
            proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
            proxy_redirect http:// https://;
        }

    }
    

配置强制http访问也走https

配置后通过https正常访问,http访问报错如下
400 Bad Request
The plain HTTP request was sent to HTTPS port

这是由于产生了497错误引起,增加一个配置如下,强制让http访问也转到https方式进行访问,
error_page 497 301 https://$http_host$request_uri;
将497,301等错误码重新定向到https

    upstream tomcatserver {
         server 127.0.0.1:8801 max_fails=3 fail_timeout=3s;
         server 127.0.0.1:8802 max_fails=3 fail_timeout=3s;         
    }
    
    server {
        listen       8888 ssl;
        server_name  localhost;
        
        ssl_certificate      /usr/local/nginx/ssl/nginx.pem;
        ssl_certificate_key  /usr/local/nginx/ssl/nginx.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;
        
        error_page 497 301 https://$http_host$request_uri;

        location / {
            proxy_pass http://tomcatserver/;
            client_max_body_size  500m;
            proxy_connect_timeout 300;
            proxy_http_version 1.1;
            proxy_send_timeout 300;
            proxy_read_timeout 300;
            proxy_set_header    Host             $http_host;
            proxy_set_header    X-Real-IP        $remote_addr;
            proxy_set_header    X-Real-Port      $remote_port;
            proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
            proxy_redirect http:// https://;
        }

    }

你可能感兴趣的:(【Nginx】,nginx,https,ssl)