【问题标题】:nginx: redirect everything from http to https, except one url-patternnginx:将所有内容从 http 重定向到 https,除了一个 url 模式
【发布时间】:2015-01-09 09:24:35
【问题描述】:

我有一个只能通过 HTTPS 访问的网站,除了一个 URL 模式(因为我在某些页面上有 http-iframe,我想避免安全警告)

E.g. this pages should be redirected to https:
http://example.com
http://example.com/a/this-is-an-article
http://example.com/v/this-is-a-video

This pages should not be redirected to https (or should be redirected form https to http)
http://example.com/l/page-with-unsafe-iframe
http://example.com/l/other-page-with-unsafe-iframe

【问题讨论】:

  • http iframe 页面是否总是在同一目录/l/?
  • 是的,它总是在 /l/ 目录下

标签: nginx


【解决方案1】:

如果 iframe 页面始终位于同一目录中,则可以使用简单的前缀位置。

server {
    listen 443;

    location /l/ {  # redirect https iframe requests to http server
        return 301 http://$server_name$request_uri;
    }
    # ...
}

server {
    listen 80;

    location / {  # the default location redirects to https
        return 301 https://$server_name$request_uri;
    }

    location /l/ {}  # do not redirect requests for iframe location
    # ...
}

【讨论】:

  • 它可能对某人有用,但是如果您尝试将所有内容重定向到 HTTPS,除了一个(或多个)位置,请记住,如果您使用的是 PHP,请记住在其中包含 PHP 处理代码HTTP 和 HTTPS 版本的两个 server {} 块。
  • 这里有个不那么明显的技巧:上面的服务器指令的顺序很重要。我有listen 80; 一个先去,它没有工作。
  • 我将尝试用我的示例重现这一点。你能发布一个链接到你的配置吗?
  • 您的配置中的其他内容可能会造成干扰。我将从以上内容开始。如果可行,请开始添加配置的元素以隔离问题。
【解决方案2】:

您可以使用 ma​​p 和简单的重定向规则,例如:

map $uri $redirect_https {
    /l/page-with-unsafe-iframe         0;
    /l/other-page-with-unsafe-iframe   0; # you can use regex here
    default                            1;
}

server {
    listen 443;

    if ($redirect_https = 0) {
       return 301 http://$server_name$request_uri;
    }

    # other code
}
server {
    listen 80;

    if ($redirect_https = 1) {
       return 301 https://$server_name$request_uri;
    }

    # other code
}

我应该提一下,301 重定向是一种与永久重写不同的好习惯。

【讨论】:

  • 可以用php控制吗?例如,我想从单个帖子中决定它是 http 还是 https。 (WordPress 网站)
  • 不是这样的。 Nginx 规则在您的 PHP 应用程序捕获请求之前起作用。
猜你喜欢
  • 2012-01-15
  • 2016-01-20
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-05
  • 1970-01-01
相关资源
最近更新 更多