nginx:将所有内容从 http 重定向到 https,除了一个 url-pattern

nginx: redirect everything from http to https, except one url-pattern

我的网站只能通过 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

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

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 重定向是一种与永久重写不同的好做法。

如果 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
    # ...
}