在 nginx 中将 http://example.com:12345 重定向到 https://example.com:12345

Sai*_*han 5 rewrite ssl nginx https

我知道这一定已经得到了回答,但是我已经搜索了很长时间,找不到答案。我猜只是没有找对地方,也许有人可以帮助我。

基本上我在非标准端口上通过 SSL 运行 phpmyadmin,在本例中为 12345。

现在我已经https://example.com:12345设置好了,一切正常。现在我想添加仅键入http://example.com:12345并重定向到 https:// 的功能。

我假设以下内容会起作用,但事实并非如此。

server {
  listen        12345;
  server_name   php.myadmin.com;

  if ( $scheme = http ) {
    rewrite ^ https://php.myadmin.com:12345$request_uri? redirect;
  }
  root         /var/www/php;

  ssl           on;

  [....]
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个400 bad request.

现在,在发布答案之前,请确保仔细查看重定向表单。检查下面链接中的陷阱。

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites

此外,如果这甚至可以在没有 if 语句的情况下完成,那就太好了:

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#using-if

the*_*ter 18

我正是这样做的。gWaldo 是正确的,但您不想通过 HTTP 提供内容,而只是重定向。诀窍是捕获 http-on-an-https-port 错误并使用它来将客户端反弹到正确的位置。

server {
    listen   12345;
    server_name  my.domain.com;

    ssl on;
    ssl_certificate /etc/ssl/certs/your.pem;
    ssl_certificate_key /etc/ssl/private/your.key;

    # If they come here using HTTP, bounce them to the correct scheme
    error_page 497 https://$server_name:$server_port$request_uri;
    # Or if you're on the default port 443, then this should work too
    # error_page 497 https://$server_name$request_uri;

    location / {
        # Your config here...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是上述问题的实际答案。我猜操作员只是放弃了,并认为他正在尝试做一些不可能的事情。 (2认同)

gWa*_*ldo 1

不幸的是,您无法使用 nginx 的单个端口来处理 http 和 https 请求

但是,您可以做的是让代理预先处理请求。这就是我们处理方案的方式:

set $real_scheme http;
if ($http_x_forwarded_proto) { set $real_scheme $http_x_forwarded_proto; }

set $target_scheme https;

if ($real_scheme != $target_scheme) {
  rewrite ^ $target_scheme://$host$request_uri redirect;
}
Run Code Online (Sandbox Code Playgroud)