g3rv4
g3rv4

Reputation: 19834

Changing the Host passed to the backend

I have my frontend server running nginx. The backend is on another machine on the same VPN. This is its config:

server {
    listen   80;
    server_name *.vpn.domain.com;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://10.8.25.102:8100/;
        proxy_redirect http://10.8.25.102:8100/ http://$server_name/;
    }   
}

I would like to pass a different host to the backend... I'd like the backend to receive, for requests done tosubdomain.vpn.domain.com the host subdomain.local.domain.com

Is there any way to do this? I'm looking for a regexp substitution (or even a substring substitution) but I'm having surprisingly little success... I thought it would be a piece of cake. I think the solution would be in the lines of

server {
    listen   80;
    server_name *.vpn.domain.com;

    set $my_host $http_host;
    replace $my_host .vpn. .local.

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $my_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://10.8.25.102:8100/;
        proxy_redirect http://10.8.25.102:8100/ http://$server_name/;
    }   
}

It's just that I haven't found yet the proper syntax for replace $my_host .vpn. .local. I don't really care about multiple substitutions... I won't have a.vpn.a.vpn.domain.com

Upvotes: 0

Views: 928

Answers (1)

g3rv4
g3rv4

Reputation: 19834

I finally figured it out, I can do

if ($http_host ~ ^(.*)\.vpn\.(.*)$) {
    set $my_host $1.local.$2;
}

And then, as there're CSRF validations in place, I also need to rewrite the Referer... so this is how it ended up looking

server {
    listen   80;
    server_name *.vpn.domain.com;

    set $my_host $http_host;
    if ($http_host ~ ^(.*)\.vpn\.(.*)$) {
        set $my_host $1.local.$2;
    }

    set $referer $http_referer;
    set $referer_host no;
    if ($http_referer ~ ^(https?://)([^/]+)(/.*)$) {
        set $referer_host $2;
        set $rewritten_referer $1$my_host$3;
    }
    if ($referer_host = $http_host) {
        set $referer $rewritten_referer;
    }

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $my_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Referer $referer;
        proxy_set_header IS_SECURE no;
        proxy_pass http://10.8.25.102:8100/;
        proxy_redirect https://$my_host/ https://$http_host/;
        proxy_redirect http://$my_host/ http://$http_host/;
    }
}

Upvotes: 1

Related Questions