【问题标题】:Redirect a http request to a website from within an iframe with a Reverse Proxy in front of the site在网站前面使用反向代理将 http 请求从 iframe 中重定向到网站
【发布时间】:2019-02-27 07:28:44
【问题描述】:

我在网站前使用 nginx 作为反向代理,并拦截网站上存储的文件的下载/预览请求。下载请求来自 iframe,如果用户未获得授权,我会将它们重定向到注销页面。但这不会将主页(iframe 之外)带到注销页面。知道该怎么做吗?

【问题讨论】:

    标签: html http nginx proxy reverse-proxy


    【解决方案1】:

    如果用户未获得授权,您可能希望从 iframe 向其父级发送消息。收到消息后,您会将父窗口重定向到注销页面。一个示例实现是found here

    但是,如果您无法修改 iframe 页面的源代码,这将变得更加困难。由于您使用的是 nginx,因此一种解决方案是使用 ngx_http_sub_module 模块进行脚本注入。此模块将响应中的一个字符串替换为另一个字符串。注意这个模块默认不包含,你可能需要用--with-http_sub_module参数构建nginx。请参阅module page 了解更多信息,包括示例。

    iframe 需要一行:

    parent.postMessage( "redirect", "http://www.your-domain.com" );
    

    要使用 nginx 注入它,您可以尝试:

    location / {
        sub_filter '</head>' '<script language="javascript">parent.postMessage( "redirect", "http://www.your-domain.com" );</script></head>';
        sub_filter_once on;
    }
    

    父窗口需要相应的代码:

    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[ eventMethod ];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
    // Listen to message from child window
    eventer( messageEvent, function( e ) {
        // normally if the message was meant to come from your domain
        // you would check e.origin to verify that it's not someone
        // sending messages you don't want
        if ( e.data = "redirect" ) {
            window.location.replace( "your-logout-url" );
        }
    }, false );
    

    更高级的解决方案可能会在消息中包含重定向 url;然后你可以处理重定向到不同位置的 iframe。

    【讨论】:

    • 这里的问题是我无法控制网站本身。我在 nginx 代理中编写模块来拦截请求并采取适当的措施。我将如何将此 JS 插入 iframe 或其父窗口?
    • @user1295872 很公平。更新了 nginx 代码注入解决方案
    • @jla ngx_http_sub_module 可以处理 https 请求吗?
    猜你喜欢
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    相关资源
    最近更新 更多