Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx proxy pass to external url

I have configured my nginx on amazon ec2 for the url www.example1.com . I need to proxy pass www.example1.com/blog to my blogging host www.example2.com/blog which is hosted on bluehost ( shred hosting ) without changing the url in browser. Is it possible ?

I tried many different combinations like

location /blog {
    proxy_pass http://www.example2.com;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

without any luck.

I could see in the log that nginx is trying to map to the IP instead of the domain which is the reason for the failure as shared hosting cannot recognize the ip but domain name.

Any input/help will be really appreciated.

like image 213
Amrish Patel Avatar asked Jul 13 '16 07:07

Amrish Patel


People also ask

What is proxy_pass in Nginx?

A simple example A proxy_pass is usually used when there is an nginx instance that handles many things, and delegates some of those requests to other servers. Some examples are ingress in a Kubernetes cluster that spreads requests among the different microservices that are responsible for the specific locations.

How do I bypass Nginx's requirement for hosts to be available?

You can circumvent nginx's requirement for all hosts to be available at startup by using variables inside the proxy_pass directives. HOWEVER, for some unfathomable reason, if you do so, you require a dedicated resolver directive to resolve these paths. For Kubernetes, you can use kube-dns. kube-system here.

What is an example of a proxy_pass?

A simple example. A proxy_pass is usually used when there is an nginx instance that handles many things, and delegates some of those requests to other servers. Some examples are ingress in a Kubernetes cluster that spreads requests among the different microservices that are responsible for the specific locations.

What port does Nginx run on?

My current setup is one single site, lets call that http://production.com, that's being served by Nginx on port 80 as a static cache and Apache in the background on port 8080 localhost, nothing fancy really and this works very well.


1 Answers

I'll give my answer here.

The problem you meet is because $http_host in proxy_set_header Host $http_host; uses the host in your original request header, but what you really need is the host for www.example2.com. $proxy_host will use the host in your proxy_pass directive. see Embedded Variables at the bottom http://nginx.org/en/docs/http/ngx_http_proxy_module.html

$proxy_host

name and port of a proxied server as specified in the proxy_pass directive;

And the reason it is not working for example1.com but www.example1.com I guess is because you didn't put the value example1.com in server_name directive.

like image 161
Lution Avatar answered Sep 17 '22 12:09

Lution