【问题标题】:nginx Redirect specific subdomain and pathnginx 重定向特定子域和路径
【发布时间】:2022-01-11 12:26:13
【问题描述】:

我们的 nginx 配置为具有自己的子域的多个站点提供服务。

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  server_name ~^(?P<sub>.+)\.(example1|example2)\.com$;
  root /var/www/instances/$sub;

  ...
}

我想将一个特定的子域及其路径重定向到不同的站点,但我不知道如何编写检查。我需要检查主机部分,然后检查路径以确定重定向应该到达的位置。

地图看起来像这样:

Old URI New URI
sub1.example1.com/wiki/0/$path newSub1.example1.com/wiki/0/$path
sub1.example1.com/wiki/20/$path newSub2.example1.com/wiki/0/$path

$path 只是请求 URI 的其余部分

sub1.example1.com 的所有其他请求都应该像以前一样工作。

【问题讨论】:

    标签: nginx redirect


    【解决方案1】:

    显而易见的解决方案是将sub1.example1.com 拆分为单独的server 块。正如您将在 this document 中看到的那样,具有确切名称的 server_name 始终优先于具有正则表达式的 server_name

    这意味着有两个 server 块具有几乎相同的内容,但这可以通过使用 the include directive 来缓解。


    或者,您可以使用a map directive 测试$host$request_uri 的值。 效率较低,因为您将在每个站点中测试 URL。

    例如:

    map $host$request_uri $redirect {
        default 0;
        ~*^sub1.example1.com/wiki/0/(?<path>.*)$ //newSub1.example1.com/wiki/0/$path;
        ~*^sub1.example1.com/wiki/20/(?<path>.*)$ //newSub2.example1.com/wiki/0/$path;
    }
    
    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        server_name ~^(?P<sub>.+)\.(example1|example2)\.com$;
        root /var/www/instances/$sub;
        if ($redirect) { return 301 $scheme:$redirect; }
    
        ...
    }
    

    【讨论】:

    • 感谢小费。我将尝试使用第二个 server
    猜你喜欢
    • 2020-12-30
    • 2016-07-30
    • 1970-01-01
    • 2016-05-27
    • 2019-04-04
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多