【问题标题】:redirect all traffic for a certain domain using nginx使用 nginx 重定向某个域的所有流量
【发布时间】:2016-06-13 19:34:30
【问题描述】:

我目前正在使用 nginx 并尝试重定向所有流量,例如firstdomain.org 到 seconddomain.org 使用简单的重定向可以正常工作,但我现在还希望它能够处理 URI、方案和子域。

例如

http(s)://firstdomain.org/ 重定向到http(s)://seconddomain.org/http(s)://firstdomain.org/test 重定向到 http(s)://seconddomain.org/testhttp(s)://test.firstdomain.org/ 重定向到 http(s)://test.seconddomain.org/ 等等..

我目前的设置是这样的:

server {
    listen 80;
    listen 443 ssl;
    server_name ~^(?<sub>\w+)\.firstdomain\.org$, firstdomain.org;

    ssl_certificate /path/to/certificate;
    ssl_certificate_key /path/to/certificatekety;

    location / {
        if ($sub = '') {
                return 301 $scheme://seconddomain.org$request_uri;
        }
        return 301 $scheme://$sub.seconddomain.org$request_uri;
    }
}

这是重定向没有子域的链接就好了,但只要它是例如http(s)://test.subdomain.orghttp(s)://test.subdomain.org/test 它不再起作用了。

我有什么遗漏的吗,或者 nginx 是否支持更简单的方法来实现我想要做的事情?

【问题讨论】:

    标签: redirect nginx webserver url-redirection http-redirect


    【解决方案1】:

    您可以通过在$sub 中捕获. 来简化:

    server {
        listen 80;
        listen 443 ssl;
        server_name ~^(?<sub>\w+\.)?firstdomain\.org$;
    
        ssl_certificate /path/to/certificate;
        ssl_certificate_key /path/to/certificatekety;
    
        return 301 "$scheme://${sub}seconddomain.org$request_uri";
    }
    

    【讨论】:

    • 这行得通,非常感谢!请注意:您似乎还需要将firstdomain.org 添加到server_name,否则它不会重定向普通的http(s)://firstdomain.org 请求。
    • @Luca 对不起。我在正则表达式中添加了 ? 以使捕获成为可选。
    • 我再次删除了firstdomain.org 并添加了?。现在一切都按预期工作。谢谢!
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2016-09-23
    • 2015-01-04
    • 2016-10-30
    相关资源
    最近更新 更多