Nginx 配置 HTTP 跳转 HTTPS

本文介绍 Nginx 访问 HTTP 跳转 HTTPS 的 4 种配置方式。

rewrite

Nginx rewrite 有四种 flag:

break:在一个请求处理过程中将原来的 url 改写之后,再继续进行后面的处理,这个重写之后的请求始终都是在当前这一个 location 中处理
last:相当于一个新的 request,需要重新走一遍 server,提供了一个可以转到其他 location 的机会
redirect:表示 302 temporarily redirect
permanent:表示 301 permanently redirect
要使用 HTTP 跳转 HTTPS,当然是需要 301 跳转,即使用 permanent 这个标签:

rewrite  ^(.*)  https://$server_name$1 permanent;

提醒:以上配置涉及到三个本文并未提及的点:rewrite 用法、全局变量、正则匹配。

301 状态码

Nginx 使用 ruturn ${http_code} 指定对应状态码的处理。这里我们使用 return 301 指定 301 重定向的目标:

return  301  https://$server_name$request_uri;

497 状态码

当 server 只允许 HTTPS 请求时,基于 HTTP 的访问会被 Nginx 返回 497 错误。这时我们使用 error_page 将访问重定向至 HTTPS 上:

error_page  497  https://$server_name$request_uri;

meta

还有一种方式是,返回一个写入 meta 标签的 html 页面,让浏览器跳转。和上面三种方式不同,此方案不在 Nginx 上进行跳转,节约服务器资源,而缺点是不能写入 $request_uri 变量,只能跳转到固定地址。

server {
    ...

    index  meta.html;
    error_page 404 meta.html;
}

在要返回的 meta.html 中写入:

<html>
  <meta http-equiv="refresh" content="0; url=${你要跳转的目标地址}">
</html>

本站就使用这个方案,所以我是这样写的:

<html>
  <meta http-equiv="refresh" content="0; url=https://db.ci/">
</html>
点赞