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?
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.
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 .
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With