【问题标题】:Redirecting in nginx results in errors在nginx中重定向会导致错误
【发布时间】:2020-01-14 08:50:16
【问题描述】:

环境:Ubuntu 18.04、nginx、WordPress

WordPress 在https://www.example.org 运行良好。另外,定义如下规则将http指向https:

server {
  if ($host = www.example.org) {
    return 301 https://$host$request_uri;
  } # managed by Certbot


  listen 80;
  server_name www.example.org;
  return 404; # managed by Certbot
}

这样,用户对http://www.example.org 的请求会自动重定向到https://www.example.org

现在,我正在尝试定义一个规则,以便 https://example.org 也可以重定向到 https://www.example.org

这是我的新 nginx 规则:

server {
  listen 443 ssl;

  server_name example.org;
  return 301 https://www.example.org$request_uri;
}

但是,这似乎会破坏整个网站。即使是之前运行良好的https://www.example.org,也会给出“无法访问此站点”的错误。

这是来自 nginx error.log 的最后一个错误:

在 SSL 握手时侦听 SSL 端口的服务器中未定义“ssl_certificate”,客户端:blah,服务器:0.0.0.0:443

回顾一下,

https://www.example.org works fine
http://www.example.org properly gets redirected to https://www.example.com
https://example.org does not work. It should also have been redirected to https://www.example.org

有人可以告诉我我做错了什么吗?问候。

【问题讨论】:

  • 您需要在.conf中定义SSL证书,您使用的是哪些证书?我猜letsencrypt 通过注释行。它应该在其中设置了您需要包含的路径。
  • 您希望每个请求/uri 都使用 SSL 吗?如果是这样的话,可能会简单得多。

标签: nginx


【解决方案1】:

您尚未指定是否需要重定向所有 URI,但这里有几个选项。确保在进行这些更改后重新启动 nginx 服务。

特定 URI

server {
    listen 80;
    server_name example.org www.example.org;
    return 301 https://example.org$request_uri;
}

所有 URI

server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

【讨论】:

  • 非常感谢您的帮助。诀窍是将 example.org 和 www.example.org 添加在一起。
  • @Peter 有一种感觉,那就是它的关键。如果其他人有同样的问题,您会更新标题以更具体吗?诸如“在 nginx 中重定向多个 URI 会导致错误”之类的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多