在 Nginx 中将 HTTP 重定向到 HTTPS

要在 Nginx 中将 HTTP 重定向到 HTTPS,你可以使用以下配置:

server {

listen 80 default_server;

server_name your_domain.com www.your_domain.com;

return 301 https://server_namerequest_uri;

}

server {

listen 443 ssl;

server_name your_domain.com www.your_domain.com;

ssl_certificate /path/to/your/ssl/certificate;

ssl_certificate_key /path/to/your/ssl/certificate/key;

Additional SSL configuration goes here

location / {

Your website root goes here

root /path/to/your/website;

index index.html index.htm;

}

}

上面的配置做了以下事情:

  1. 第一个 server 块监听 80 端口(HTTP)。当用户访问 http://your_domain.comhttp://www.your_domain.com 时,Nginx 会返回 301 重定向,将请求重定向到 HTTPS。
  2. 第二个 server 块监听 443 端口(HTTPS)。它设置了 SSL 证书的路径,以及其他 SSL 相关的配置项。
  3. 在第二个 server 块中,location / 部分定义了网站的根目录。你需要将 /path/to/your/website 替换为你实际的网站根目录路径。

注意:

  • 你需要将 your_domain.com 替换为你自己的域名。
  • /path/to/your/ssl/certificate/path/to/your/ssl/certificate/key 替换为你的 SSL 证书和密钥的实际路径。
  • 根据你的具体需求,你可能需要调整其他 SSL 相关的配置项。

在应用新的配置后,重启 Nginx 服务器以使更改生效。之后,当用户访问 HTTP 版本的网站时,Nginx 将自动将他们重定向到 HTTPS 版本。

相关推荐
牛奶3 小时前
HTTPS你不知道的事
前端·https·浏览器
喵个咪1 天前
Go-Wind HTTP 服务器从入门到精通
后端·http·go
AlfredZhao3 天前
生产环境里,为什么不建议把普通端口直接暴露到公网?
linux·https·443·80
Goodbye7 天前
大模型无状态架构:从 HTTP 协议到 Harness AI 工程的深度解析
http
Avan_菜菜8 天前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
ping某12 天前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx
霜落长河13 天前
抛弃TCP改用UDP,HTTP3怎么了?
http
程序员mine14 天前
HTTPS-TLS加密与证书完全指南(中)
网络协议·https·ssl
之歆14 天前
现代 HTTP 客户端深度解析:Fetch 与 Axios
chrome·网络协议·http
難釋懷14 天前
Nginx反向代理中的容错机制
运维·nginx