19

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.

Falko
  • 17,076
  • 13
  • 60
  • 105
Amrish Patel
  • 442
  • 1
  • 6
  • 14
  • 7
    Try change ``proxy_set_header Host $http_host;`` to ``proxy_set_header Host $proxy_host;`` – Hammer Jul 13 '16 at 09:41
  • Thank you so much! It works perfectly! I am not sure if I am allowed to ask another question related with this. It does not redirect when I write http:// example1.com however, it gets redirected for http:// www.example1.com and www.example1.com. My apologies if I am not allowed to do so. – Amrish Patel Jul 14 '16 at 10:54

1 Answers1

14

The problem 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.

Anthony
  • 13,434
  • 14
  • 60
  • 80
Hammer
  • 1,514
  • 2
  • 14
  • 22
  • Thanks for detailed answer. I tried writing example1.com in server like, server_name example1.com www.example1.com; However, www.example1.com gets content from www.example2.com. But, http:// example1.com still gives original contents. – Amrish Patel Jul 14 '16 at 13:28
  • @AmrishPatel Paste your whole server block – Hammer Jul 14 '16 at 16:39
  • @AmrishPatel :: Was this issue resolved ? I have similar problem https://stackoverflow.com/questions/52391068/nginx-reverse-proxy-to-apache-wordpress-works-but-proxy-pass-to-external-url-fai – Vikram Alva Sep 19 '18 at 07:17
  • @Lution It works like `return` (redirect), I mean the url changes during this procedure, is there any way to proxy to another link without changing url? – Benyamin Jafari Jul 04 '20 at 10:40