如何配置nginx将子域代理到子目录?

时间:2019-05-16 01:03:33

标签: nginx reverse-proxy

我需要从(?<account_subdomain>).example.com/foo之类的任意子域代理到目录example.com/account/$account_subdomain/foo。我下面的所有尝试都将浏览器从acme.example.com转到下面的递归URL:

https://acme.example.com/account/acme/account/acme/account/acme/account/acme/account/acme/account/...

现有问题/答案要么使用root来提供文件,使用重定向,要么对我不起作用。例如,有人遇到类似的递归问题,并通过不传递请求主机来解决它,这就是为什么我在下面对proxy_set_header Host "example.com";进行硬编码。

上游服务器,http-> https重定向和裸域:

upstream app_server {
    server localhost:3000 fail_timeout=0;
}

server {
    listen 80;
    server_name "~^(?<subdomain>.*\.)example.com";
    rewrite ^(.*) https://$subdomain$server_name$1 permanent;
}

server {
    server_name example.com www.example.com;
    listen 443 ssl;

    # ...

    location /static {
        autoindex on;
        alias /home/path/to/static/on/disk;
    }
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host "example.com";
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

尝试1次用于子域代理,重写+ proxy_pass

server {
    server_name "~^(?<account_subdomain>[a-zA-Z\d]+)\.example.com$";
    listen 443 ssl;

    # ...

    location /static {
        autoindex on;
        alias /home/path/to/static/on/disk;
    }
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host "example.com";
        proxy_redirect off;
        rewrite (^.*) /account/$account_subdomain$1;  # also tried 'break;' and 'last;'
        proxy_pass http://app_server;
    }
}

仅使用proxy_pass尝试2次子域代理

server {
    server_name "~^(?<account_subdomain>[a-zA-Z\d]+)\.example.com$";
    listen 443 ssl;

    # ...

    location /static {
        autoindex on;
        alias /home/path/to/static/on/disk;
    }
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host "example.com";
        proxy_redirect off;
        proxy_pass http://app_server/account/$account_subdomain$request_uri;
    }
}

仅使用重写尝试3个子域代理

server {
    server_name "~^(?<account_subdomain>[a-zA-Z\d]+)\.example.com$";
    listen 443 ssl;

    # ...

    location /static {
        autoindex on;
        alias /home/path/to/static/on/disk;
    }
    location /account/ {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host "example.com";
        proxy_redirect off;
        proxy_pass http://app_server;
    }
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host "example.com";
        proxy_redirect off;
        rewrite (^.*) /account/$account_subdomain$1 last;  # also tried 'break;' and 'last;'
    }
}

其中一些配置确实到达了上游,并给了我404,其余的导致nginx本身返回500。理想情况下,使用浏览器导航到acme.example.com/foo会导致浏览器地址中的https://acme.example.com/foo栏,但返回的页面来自http://localhost:3000/account/acme/foo

0 个答案:

没有答案