登瀛网

在Nginx中将http://zh30.com:443跳转到https://zh30.com:443

2022-08-25

有小伙伴反应我博客半年没更新了,借此机会赶紧水一篇。

另有小伙伴求助于我一个这样的问题,说在使用http://协议外加443端口访问时,nginx会报错提示:

“400 Bad Request The plain HTTP request was sent to HTTPS port”

这个错误是指请求错误,http协议的请求被发送到了https的端口。在Nginx中,不能在一个端口同时处理http和https请求。按正常浏览来说也不可能会有这种链接(请求)的存在。

nginx在使用https的端口的http访问时,会产生一个内部报错码497,所以在监听443端口的server中,将这个497错误跳转出去即可。

使用nginx的error_page指令来捕捉497错误并重定向如下:

error_page 497 https://$server_name$request_uri;

如果是非标准端口,可能需要在$server_name后追加:$server_port。

error_page 默认使用302跳转,如果想指定其它状态码,如301,可以在错误码后添加 =301,如:

error_page 497 =301 https://$server_name$request_uri;

示例如我的博客:

listen 443 ssl;
server_name zh30.com www.zh30.com;
error_page 497 https://$server_name$request_uri;

index index.html index.htm index.php;

加上上面这句后,重新reload配置后,浏览器访问http://zh30.com:443时将直接跳转到https://zh30.com, 不再会有400 bad request错误产生了,至此问题解决。

加一个参考链接,显得专业:

关于ssl及497错误码:http://nginx.org/en/docs/http/ngx_http_ssl_module.html

关于error_page:http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page