Nginx将特定子域重定向到特定位置

fv2wmkja  于 2023-03-01  发布在  Nginx
关注(0)|答案(1)|浏览(132)

我希望这样,当用户键入task-manager.example.com时,他们会自动重定向到location /api/,而不必键入task-manager.example.com/api的完整路径。
对于example.comwww.example.com,我希望所有请求都被定向到location /,而不管用户是否键入example.com/api。任何对example.com/apiwww.example.com/api的请求都应该被自动重定向到example.com/www.example.com/
Nginx是否可以配置为实现此功能?
以下是我的当前配置:

server
{
    server_name example.com www.example.com task-manager.example.com;

    location /
    {
        # Frontend application
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_pass http://localhost:9091;
    }

    location /api/
    {
        # Backend application
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_pass http://localhost:9090;
    }

    # some Certbot SSL configuration ...
}

server
{
    if ($host = www.example.com) {
        return 301 https://$host/;
    } # managed by Certbo

    if ($host = example.com) {
        return 301 https://$host/;
    } # managed by Certbo

    if ($host = task-manager.example.com) {
        return 301 https://$host/api;
    } # managed by Certbo

    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com task-manager.example.com;
    return 404; # managed by Certbot
}
5fjcxozz

5fjcxozz1#

我可以通过将if conditions移动到相关的location blocks来解决我的问题。这允许我为特定的主机指定重定向到特定的URI。
这是我的新配置:

server
{
    server_name example.com www.example.com task-manager.example.com;

    location /
    {
        if ($host = task-manager.example.com) {
            return 301 /api;
        }

        # Frontend application
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_pass http://localhost:9091;
    }

    location /api/
    {

        if ($host = www.example.com) {
            return 301 /;
        }

        if ($host = example.com) {
            return 301 /;
        }

        # Backend application
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_pass http://localhost:9090;
    }

    # here is usually some Certbot SSL configuration ...
}

server
{
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com task-manager.example.com;
    return 301 https://$host$request_uri;
}

相关问题