nginx_非标准端口_同端口_http_自动跳转_https

参考

背景

小目标:在只监听一个端口的情况下,将http访问跳转为https。

一般情况下http协议使用80端口,https协议443端口。要实现http强制转https是非常简单的事,随便都可以找到很多方案。使用非默认端口时这就变得有点麻烦了。

把 https 的网站设置在非标准端口。访问的时候需要带上端口号。
总是因为忘了打上 https:// 前缀导致访问失败。
希望在没打https://前缀时,都能正常访问。

曾经看过一篇文章讲述如何让http 和https 在一个端口上工作。原理大概是以tcp方式监听,检查传入的前几个字节,从而判断出是HTTP还是HTTPS的请求,再将数据转发到相应端口上。这种方式非常强悍,但如果仅仅是让http跳转到https有点杀鸡用牛刀的感觉。

最近无意中看到一篇有关Nginx的文章,其中提到了一个497的状态码:

Nginx internal code used for the plain HTTP requests that are sentto HTTPS port to distinguish it from 4XX in a log and an error pageredirection.

由此可见Nginx内部是可以检测到错误的请求的。因此可以尝试通用error_page去拦截。 配置代码:

error_page 497 https://$host:$server_port$uri$is_args$args;

重启Nginx 后,使用浏览器以http访问网站,跳转了!!!

由此证明用error_page拦截497实现http跳转https是可行的。

官方文档

相同端口 http 跳 https

默认497错误,是返回400 Bad Request: The plain HTTP request was sent to HTTPS port
可以修改这个错误处理。 在 server { .. } 中加入一行。

  • error_page 497 https://$host$request_uri; 默认用302,临时重定向
  • error_page 497 =301 https://$host$request_uri; 永久重定向
  • error_page 497 =307 https://$host$request_uri; 临时重定向,不改变请求的方法(如post还是post)

如果重定向后,没有带上正确的端口号,则显式的加上端口号 $server_port

  • error_page 497 https://$host:$server_port$request_uri;

还有一种写法,

  • error_page 497 https://$host:$server_port$uri$is_args$args;

最终写法:

posted @ 2022-04-27 09:15  我命由我不由天—hao  阅读(784)  评论(0编辑  收藏  举报