一般情况下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)