nginx 基于子域名的条件重写

nginx 基于子域名的条件重写

我有当前的 nginx 配置,它将所有子域请求更改为特定模式(foo.example.com-> www.example.com/co/home/foo):

server {
    listen 80;
    server_name *.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /etc/ssl/examplecom_bundle.crt;
    ssl_certificate_key /etc/ssl/examplecom.key;

    server_name ~^(?<subdomain>[^.]+)\.example\.com$;
    return 301 https://www.example.com/co/home/$subdomain$request_uri;
}

我需要添加其他逻辑来将特定子域重定向到不同的 URL ( bar.example.com-> www.example.com/co/bar)。在我看来,它看起来像这样:

server_name ~^(?<othersubdomain>(bar|baz))\.example\.com$;
return 301 https://www.example.com/co/$othersubdomain$request_uri;

关于如何将这一切结合起来使其发挥作用,有什么建议吗?

答案1

感谢@alexey-ten的评论,以下操作有效:

server {
    listen 80;
    server_name *.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /etc/ssl/examplecom_bundle.crt;
    ssl_certificate_key /etc/ssl/examplecom.key;

    server_name ~^(?<subdomain>(bar|baz))\.example\.com$;
    return 301 https://www.example.com/co/$subdomain$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /etc/ssl/examplecom_bundle.crt;
    ssl_certificate_key /etc/ssl/examplecom.key;

    server_name ~^(?<subdomain>[^.]+)\.example\.com$;
    return 301 https://www.example.com/co/home/$subdomain$request_uri;
}

相关内容