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

tie*_*enb 35 nginx

我有一个只能通过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
Run Code Online (Sandbox Code Playgroud)

Col*_*ney 55

如果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
    # ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这里有一个不太明显的技巧:**上面服务器指令的顺序很重要**。我先尝试了“听80;”,但没有成功。 (2认同)

Dmi*_*y Z 14

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

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
}
Run Code Online (Sandbox Code Playgroud)

我应该提一下,301重定向是一个很好的做法,不像永久重写.