Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Host header in nginx reverse proxy

Tags:

nginx

I am running nginx as reverse proxy for the site example.com to loadbalance a ruby application running in backend server. I have the following proxy_set_header field in nginx which will pass host headers to backend ruby. This is required by ruby app to identify the subdomain names.

location / {     proxy_pass http://rubyapp.com;     proxy_set_header Host $http_host; } 

Now I want to create an alias beta.example.com, but the host header passed to backend should still be www.example.com otherwise the ruby application will reject the requests. So I want something similar to below inside location directive.

if ($http_host = "beta.example.com") {     proxy_pass http://rubyapp.com;     proxy_set_header Host www.example.com; } 

What is the best way to do this?

like image 386
Basil Avatar asked Jan 16 '13 06:01

Basil


People also ask

How do I change the hostname in nginx?

Configure the first website to listen on host header http://myfirstwebsite . To achieve this, change the server_name in the /etc/nginx/sites-enabled/default configuration file, as shown in the following screenshot. As a reminder, you'll have to use the sudo vi /etc/nginx/sites-enabled/default command to edit this file.

Does nginx pass headers?

Passing Request HeadersBy default, NGINX redefines two header fields in proxied requests, “Host” and “Connection”, and eliminates the header fields whose values are empty strings. “Host” is set to the $proxy_host variable, and “Connection” is set to close .

What does Proxy_set_header host $host do?

The reverse is readily possible: proxy_set_header Host $host; will replace any Host variable coming back from the upstream with the hostname from the original request.

Where is nginx reverse proxy hosting?

Using Nginx as a Reverse Proxy On Ubuntu and Debian based distributions, server block files are stored in the /etc/nginx/sites-available directory, while on CentOS in /etc/nginx/conf. d directory.


Video Answer


1 Answers

You cannot use proxy_pass in if block, so I suggest to do something like this before setting proxy header:

set $my_host $http_host; if ($http_host = "beta.example.com") {   set $my_host "www.example.com"; } 

And now you can just use proxy_pass and proxy_set_header without if block:

location / {   proxy_pass http://rubyapp.com;   proxy_set_header Host $my_host; } 
like image 94
Michał Kupisiński Avatar answered Sep 18 '22 13:09

Michał Kupisiński