nginx 之 http 转 https (两种方式)

方式一:

#这种方法是http转发到https,但是http和https不能用同一个配置
server {
	listen	80;
	listen	www.xxx.com:80; #此处添加你要该链接访问的域名
	server_name  www.xxx.com  alias  xxx.com.alias;
	rewrite ^(.*) https://$server_name$1 permanent;		#此句最关键
}

方式二:

#使用同一个端口,http转https

原理:

http和https是tcp的上层协议,当nginx服务器建立tcp连接后,根据收到的第一
份数据来确定客户端是希望建立tls还是http。nginx会判断tcp请求的首写节内容
以进行区分,如果是0x80或者0x16就可能是ssl或者tls,然后尝试https握手。
如果端口开启了https,但请求过来的并不是,会抛出一个http级别的错误,
这个错误的状态码是NGX_HTTP_TO_HTTPS,错误代码497,然后在返回
response中会抛出一个400错误(因为497不是标准状态码,丢给浏览器也没
有用),这时浏览器会显示"400 Bad Request,The plain HTTP request was 
sent to HTTPS port"
server {
	listen	80 ssl;
	listen	www.xxx.com:80; 							#此处添加你要该链接访问的域名
	server_name  www.xxx.com  alias  xxx.com.alias;
	error_page 497 https://$host:8080$request_uri;		#此句最关键,重新定义端口
	#error_page 497 https://$http_host$request_uri;		#此句最关键,只是将http改为https,其他不变
}

#这里说下变量
示例:

https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1

host:没有端口的server_name :www.baidu.com
http_host:有端口的server_name :www.baidu.com
request_uri:server_name后面的部分 :/s?ie=utf-8&f=8&rsv_bp=1

发布了193 篇原创文章 · 获赞 13 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u013919153/article/details/105435507