欢迎,来自IP地址为:3.144.189.177 的朋友


Nginx HTTP服务器的一条报错“400 Bad Request: The plain HTTP request was sent to HTTPS port”,本文将讲解如何解决这个问题。从报错的字面意思上来看,是因为HTTP请求被发送到HTTPS端口,这种报错多出现在Nginx既处理HTTP请求又处理HTTPS请求的情况。

为了便于理解,我们假设这样一个场景。Nginx为web网站提供提供服务,而其中只有一个网站使用SSL协议。

以下是Nginx常用的SSL配置(出于安全原因,我们使用了示例域名),配置文件将让Nginx侦听80和443端口,并将所有的HTTP请求重定向到HTTPS。

server{
        listen 80;
        server_name example.com www.example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 443 ssl http2;
        server_name example.com www.example.com;

        root   /var/www/html/example.com/;
        index index.php index.html index.htm;

        #charset koi8-r;
        access_log /var/log/nginx/example.com/example.com_access_log;
        error_log   /var/log/nginx/example.com/example.com_error_log   error;

        # SSL/TLS configs
        ssl on;
        ssl_certificate /etc/ssl/certs/example_com_cert_chain.crt;
        ssl_certificate_key /etc/ssl/private/example_com.key;

        include /etc/nginx/ssl.d/ssl.conf;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   /var/www/html/example.com/;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {

                root   /var/www/html/example.com/;
                fastcgi_pass   127.0.0.1:9001;
                #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include         fastcgi_params;
                include /etc/nginx/fastcgi_params;

        }
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
}

以上的配置看上去都很正常,但是用户想通过80端口来访问网站时,例如使用http://example.com,那么这个用户就会在浏览器收到错误400“The plain HTTP request was sent to HTTPS port”,示例图片如下:

出现这个错误,因为每一次客户试图通过HTTP访问你的网站,这个请求被重定向到HTTPS。于是Nginx预计使用SSL交互,但原来的请求(通过端口80接收)是普通的HTTP请求,于是会产生错误。

另一方面,如果一个客户使用https://example.com访问网站,他们就不会遇到上述错误。此外,如果你有其他的网站配置为不使用SSL,Nginx会尝试使用HTTPS,这种情况下也会造成上述错误。

解决办法也很简单,就是将上面配置文中的“ ssl on ; ” 注释掉或者修改成 “ ssl off ;”,这样,Nginx就可以同时处理HTTP请求和HTTPS请求了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注