【问题标题】:Redirecting naked domains to www in Meteor with Iron Router使用 Iron Router 将裸域重定向到 Meteor 中的 www
【发布时间】:2014-07-02 00:25:27
【问题描述】:

我想将进入我网站的裸域的用户自动重定向到 www 子域。 Pre-Blaze,这是我使用 Iron Router 执行此操作的代码:

Router.onBeforeAction(function() {
    var rootDomainRegex = new RegExp(
        '^https:\\/\\/mysite.com',
        'ig'
    );
    if ( window && rootDomainRegex.test( window.location.href ) ) {
        this.stop();
        window.location = window.location.href.replace(
            rootDomainRegex,
            'https://www.mysite.com'
        );
    }
};

当我升级到 Meteor 0.8.0 和 Iron Router 的 Blaze 兼容版本时,这停止了工作。 (我用 pause() 替换了 this.stop(),但这没有帮助。)现在,当您导航到裸域时,页面只是挂起,没有控制台错误。

是否有可靠且与 Blaze 兼容的方法将用户从裸域重定向到 www? (或者也许这根本不应该在应用程序级别?)

这是我的 Blaze 后代码。 (这是当前不工作的代码。)

Router.onBeforeAction(function(pause) {

    var rootDomainRegex = new RegExp(
        '^https:\\/\\/mysite.com',
        'ig'
    );
    rootDomainRegex.lastIndex = 0;
    if ( window && rootDomainRegex.test( window.location.href ) ) {
        window.location = window.location.href.replace(
            rootDomainRegex,
            'https://www.mysite.com'
        );
        pause();
    }

});

只用一点额外信息进行编辑:我刚刚发现,对于裸域,传递给 Router.onBeforeAction() 的函数根本无法运行。

【问题讨论】:

  • 如果你在 NGINX 反向代理后面运行 Meteor,在 Nginx 中进行域重定向非常容易。

标签: meteor iron-router


【解决方案1】:

您应该粘贴更新后的代码,将 this.stop 替换为 pause。

我怀疑您的代码是否存在任何与 blaze 相关的问题,它应该可以正常工作,即使您不调用 pause,您也应该被重定向。所以这可能是因为你的正则表达式不匹配。

我猜你试图在if 语句之前调用console.log(rootDomainRegex.test(window.location.href)) 并返回true?!如果你这样做了,这就是原因,第一次调用 regex.test,它匹配返回 true,但也会增加正则表达式的 lastIndex - 因为g 标志,第二次调用test 它会尝试匹配从那个 lastIndex 并且它失败了,从不执行 window.location 部分。

HTH,尝试粘贴您现在无法正常工作的确切代码。

【讨论】:

  • 谢谢,我刚刚编辑添加了当前的实时代码。正则表达式不会在其他任何地方使用test()ed,但为了安全起见,我添加了lastIndex 重置。但这并没有帮助。
猜你喜欢
  • 2015-01-07
  • 2013-10-31
  • 1970-01-01
  • 2017-08-31
  • 2020-02-17
  • 1970-01-01
  • 2014-03-29
  • 2015-04-24
  • 1970-01-01
相关资源
最近更新 更多