Nginx – VirtualHost’s behind an nginx reverse proxy fail to resolve properly

apache-2.4nginxreverse-proxyubuntu-14.04virtualhost

I have a load balancer pair in front of 4 web servers which run nginx on port 80 and proxy to apache on port 8081 for non-static content like php code. I'm running several domains in this configuration. When I hit the domain on 80 for static content, it works fine. Nginx returns what it should. When I go to a PHP page, it always hits the default virtual host.

When I instead visit port 8081 on a php page through the load balancers it servers both php pages and static content properly.

It appears that nginx isn't properly passing off the domains to apache for it to determine what to serve. Where in my config should I be looking for this error or am I misunderstanding what is happening?

Here is my nginx proxy_params contents:

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;
proxy_set_header X-Forwarded-Proto $scheme;

My server blocks include this code:

  location ~ /\. { 
    deny all; 
  }

  location ~.*\.(3gp|gif|jpg|jpeg|png|ico|wmv|avi|asf|asx|mpg|mpeg|mp4|pls|mp3|mid|wav|swf|flv|html|htm|txt|js|css|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|xls|xlsx|pdf|iso|ico)$ {
    expires 7d;
    try_files $uri @apache;
  }

  location / {
    proxy_pass http://127.0.0.1:8081;
  }

  location @apache {
    proxy_pass http://127.0.0.1:8081;
  }

Best Answer

The proxy_params file is not included in the configuration by some sort of default include like I assumed. I've corrected the problem by adding include /etc/nginx/proxy_params to each of my locations using proxy_pass. That "proxy_set_header Host $http_host;" thing is critical.

I'd welcome a cleaner solution if anyone has one that allows me to set those in the config once instead of each time. If you can give me that, I'll give you credit.

Here is my resulting location blocks in each server block:

location ~ /\.  { deny all; }

# Serve up the static files through nginx 
# This provides speed improvements
location ~.*\.(3gp|gif|jpg|jpeg|png|ico|wmv|avi|asf|asx|mpg|mpeg|mp4|pls|mp3|mid|wav|swf|flv|html|htm|txt|js|css|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|xls|xlsx|pdf|iso|ico)$ {
  expires 7d;
  try_files $uri @apache;
}

# Try it in the local Apache on port 8081
location / {
  proxy_pass http://127.0.0.1:8081;
  include /etc/nginx/proxy_params;
}

location @apache {
  proxy_pass http://127.0.0.1:8081;
  include /etc/nginx/proxy_params;
}