Nginx配置HTTP跳转HTTPS

一般情况下http协议使用80端口,https协议443端口。要实现http强制转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://xxxxxxx:xx00;

error_page可以作为server节点的局部配置也可以放在http节点作为全局配置。
重启Nginx 后,使用浏览器以http访问网站。

配置代码如下(本文以全局配置为例):

[dft@k8s-node01-test conf]$ whereis nginx
nginx: /etc/nginx /usr/local/nginx /usr/local/nginx/sbin/nginx.old /usr/local/nginx/sbin/nginx
[dft@k8s-node01-test nginx]$ cd /usr/local/nginx/conf
[dft@k8s-node01-test conf]$ ls
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf_backup   scgi_params.default   vhosts
fastcgi.conf.default  koi-utf                 mime.types.default  nginx.conf.default  uwsgi_params          win-utf
fastcgi_params        koi-win                 nginx.conf          scgi_params         uwsgi_params.default
[dft@k8s-node01-test nginx]$ vi nginx.conf

nginx.conf如下:

user  root;
worker_processes  8;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;
       
    ######
    ## set access log format
    ######
    log_format  main '$remote_addr $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '$http_user_agent $http_x_forwarded_for $request_time $upstream_response_time $upstream_addr $upstream_status';
       
    ###http to https
    error_page 497 https://xx.x.xxx.xxx:8800;
 
}

转载自(https://www.cnblogs.com/pencile/p/Nginx_http_to_https.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值