Inactivist
Inactivist

Reputation: 10477

How to proxy proxy domain name to internal app server URL in Nginx?

I have an internal app server (Django+gunicorn) running behind an Nginx reverse proxy on a private port (listening on port 5000, for example.)

There are several Django apps installed in the app server, mapped to separate base paths. Example:

/app1
/app2

Where /app1 serves up content for domain1.com and /app2 serves content for domain2.com.

I'd like to silently reverse proxy incoming requests for specific hostnames to the related backend app, while preserving the path forwarded to the internal app server:

http://domain1.com/foo --> /app1/foo
http://domain1.com/bar/bletch --> /app1/bar/bletch

http://domain2.com/alpha/bravo --> /app2/alpha/bravo

I suppose you could say I'm trying to set up a simple 'virtual hosting' configuration but I want to use a shared back-end app server instance.

Key point: I don't want the visitor's browser to see the redirected URL structure. So when the client browser hits http://domain1.com/foo, the correct content is served up but the browser doesn't see a redirect.

I've done some basic work with Nginx (still learning) and I'm looking for example Nginx configurations demonstrating secure and efficient ways to accomplish this goal.

Upvotes: 3

Views: 5668

Answers (1)

Inactivist
Inactivist

Reputation: 10477

Based on this answer here's a configuration that seems to work as desired.

For app1 running on http://localhost:8000/app1_path :

upstream app1 {
    server 127.0.0.1:8000 fail_timeout=0;
}
server {
    listen 80;
    server_name example.com
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        rewrite ^(.*)$ /app1_path$1 break;
        proxy_pass http://app1;
    }
}

So, one could repeat this pattern as many times as desired for each hostname->app/path pair.

Upvotes: 3

Related Questions