【问题标题】:nginx location redirect all but specific domain with any subdomain and any pathnginx 位置使用任何子域和任何路径重定向除特定域之外的所有域
【发布时间】:2020-02-19 22:01:48
【问题描述】:

我正在尝试使用位置正则表达式进行重定向。我希望所有可能的路径都从 examplesite.com 重定向到 404,并且 subdomain.examplesite.com 应该重定向到我的服务器。

examplesite.com redirect
https://m.examplesite.com redirect
www.examplesite.com/something redirect
everything else redirect to 404

这是我的配置:

location ~ ^(?!(.?)examplesite.com/?(.*)) {
return 404;
}

location / {
return 302 $scheme://192.168.1.1/index.html; #this is a local web server
}

这一定是错误的,因为它会将我尝试的每个 examplesite.com 重定向到 404。

【问题讨论】:

    标签: regex nginx redirect


    【解决方案1】:

    我认为你可以试试这个 ^((?!examplesite.com).)*$ - 任何没有 examplesite.com 的 url 都可以重定向到 404,如果 URL 中有 examplesite.com 则不管它的位置然后它不会匹配。

    【讨论】:

    • 这似乎不起作用,所以我回到使用 dnsmasq 来实现这一点。我尝试了两个 location ~* ^((?!examplesite.com).)*$ 和 location ^((?!examplesite.com).)*$
    • 奇怪。我自己测试了这个正则表达式模式,它在本地和在线正则表达式模式匹配器中运行良好。
    • 我又试了一遍。它在 nginx 中不起作用,我还测试了前 3 个在线正则表达式测试器,它也不匹配。我的配置是这样的: location ^((?!examplesite.com).)*$ { return 404; } location / {我还尝试删除“其他所有”位置并留下您的建议加上这个:位置^((?examplesite.com)。)* $它也不起作用。我没有dns重定向并将配置更改为其他东西在起作用,但不是我想要的,除非我通过 dnsmasq 来做。
    • 这可能是我的错误,因为我得到了奇怪的结果。http 站点被重定向到本地服务器,而 https 站点都得到相同的响应,这是一个认证错误。我不知道你是否可以从重定向和 404 重定向都得到这个,所以我无法测试它。您对正则表达式是正确的,在 nginx 测试器站点上它按预期工作。我尝试投票,但我还没有足够的积分。
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2015-02-07
    • 2021-11-03
    • 2016-05-27
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多