Nginx proxy_pass not working for subpages

nginx

I'm trying to set up an nginx proxy_pass that does the following

url is example1.com

this needs to redirect to example2.com, but keep saying example1.com.

This works for the root page, but not for the subpages.

Here is what I have so far

server {
  listen       80;
  server_name  example1.com;
  root /home/<route>/public;
  rails_env staging;
  location / {
  proxy_pass        http://example2.com/example_one/;
  add_header 'Access-Control-Allow-Origin' *;
  add_header 'Access-Control-Allow-Methods' "GET, POST, PUT, DELETE, OPTIONS";
  add_header 'Access-Control-Allow-Headers' "X-Requested-With, X-Prototype-Version";
  add_header 'Access-Control-Max-Age' 1728000;
  rewrite ^(/api/)(.*)$ http://example2.com/api/$2 permanent;
  }
gzip on;
 location ^~ /assets/ {
  expires max;
   add_header Cache-Control public;
 }
#  root /home/<root>/public;
#  rails_env staging;
}
#  } 

What we want is for all example1.com/page to go to the correct page on example2.com/page but keep displaying example1 in the url

Best Answer

I think the culprit is your rewrite rule :

rewrite ^(/api/)(.*)$ http://example2.com/api/$2 permanent;

Here you do an explicit Redirect, so it will change the URL in the browser.

Even if you don't explicitely call /api/ in your browser, my guess is that you have some code in your pages that use it.

So, if you want to modify the proxy_pass path for the particular /api/ location, you should define its own location block :

location ^~/api/ {
   proxy_pass http://example2.com/api/;
}

And, then, remove the rewrite rule you have in your config.

Related Topic