随着互联网安全要求的提升,HTTPS(加密的 HTTP)已经成为现代网站的标配。但不少用户仍会通过 HTTP 访问网站,因此我们需要确保他们被自动重定向到 HTTPS。
本篇博客将介绍如何通过 Nginx 配置实现 HTTP 到 HTTPS 的自动重定向,并说明变量含义、注意事项及完整配置。
✳️ 为什么要从 HTTP 重定向到 HTTPS?
- 安全性:HTTPS 提供了加密传输,防止中间人攻击。
- SEO 友好:Google 明确表示优先收录 HTTPS 页面。
- 浏览器兼容性:现代浏览器对 HTTP 页面标记为"不安全"。
🛠️ 环境准备
确保你已经具备以下条件:
- 安装好的 Nginx(1.14+ 推荐)
- 有效的 SSL 证书(如使用 Let's Encrypt)
📄 完整的 Nginx 配置示例(含重定向)
将下面文件放在 /etc/nginx/conf.d 并取名为 ssl.conf。
nginx
# HTTP 服务器:监听 80 端口并重定向到 HTTPS
server {
listen 80;
server_name example.com www.example.com;
# 永久重定向到 HTTPS
return 301 https://$host$request_uri;
}
# HTTPS 服务器:监听 443 端口,启用 SSL
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL 证书配置(以 Let's Encrypt 为例)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ##密钥所在服务器的绝对路径
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ##密钥所在服务器的绝对路径
# 推荐的 SSL 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
🔍 $host
与 $request_uri
是什么?
在配置中这行代码很关键:
nginx
return 301 https://$host$request_uri;
它表示将所有 HTTP 请求永久重定向到 HTTPS。下面解释两个变量:
🔸 $host
- 表示请求头中的 Host 字段;
- 代表用户请求的域名,比如
example.com
或www.example.com
; - 如果没有显式的 Host 请求头,Nginx 使用
server_name
的第一个值。
🔸 $request_uri
- 表示原始请求路径 + 查询字符串(如
/login?user=admin
); - 不包含协议和主机信息,仅表示 URI 部分。
✅ 举例说明
用户请求:
http://example.com/shop?id=123
Nginx 返回:
HTTP/1.1 301 Moved Permanently
Location: https://example.com/shop?id=123
等效于:
nginx
return 301 https://example.com/shop?id=123;
🧪 调试小技巧
如果你想临时查看 $host
和 $request_uri
的值,可以添加如下调试配置:
nginx
location /debug {
return 200 "host: $host\nuri: $request_uri\n";
}
访问 http://example.com/debug
即可看到实际变量值。
✅ 总结
通过两段简单的配置,Nginx 就能实现自动将 HTTP 请求安全地重定向到 HTTPS,提高网站安全性和用户体验。
📌重点小结:
- 使用
$host$request_uri
保留原始访问地址; - 使用
return 301
实现永久重定向; - 配置 HSTS 提高安全性;
- 建议启用 HTTP/2 以提升性能。