nginx – Reverse Proxy Folder Configuration

nginxreverse-proxy

I'm trying to access a server behind another with a reverse proxy. The "main" server is behind mydomain.com and I would like to access the second one by using mydomain.com/test. For the moment just mydomain.com/test works.

But if I try to access mydomain.com/test/myfiles, I'm redirected to mydomain.com/myfiles which doesn't exist because this url target the "main" server, so 404 not found appears. I tried multiple thing with proxy_redirect, rewrite but nothing worked.

server {
    listen   80;
    index index.php index.html index.htm;
    root /path/to/content;
    server_name localhost mydomain.com;

    location / {
        try_files $uri $uri/ =404; #/index.html;
    }

    location /test/ {
        proxy_pass http://192.168.1.202/;
        proxy_set_header Host $host;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

curl -I "http://192.168.1.202" -H "Host: mydomain.com" on the main server gives :

HTTP/1.1 301 Moved Permanently
Server: nginx/1.2.1
Date: Sun, 02 Nov 2014 15:02:56 GMT
Content-Type: text/html
Content-Length: 184
Location: example.com/myfiles
Connection: keep-alive

Best Answer

The issue is that when you use a trailing slash with the proxy_pass directive, the default behaviour for proxy_redirect is that the following :

location /test/ {
    proxy_pass http://192.168.1.202/;
    proxy_set_header Host $host;
}

Is the same as :

location /test/ {
    proxy_pass http://192.168.1.202/;
    proxy_redirect http://192.168.1.202/ /test/;
    proxy_set_header Host $host;
}

So given the curl output, you must set this up :

location /test/ {
    proxy_pass http://192.168.1.202/;
    proxy_redirect http://$host/ /test/;
    proxy_set_header Host $host;
}