Nginx Reverse Proxy with Authentication

So you have an internal device the web-gui of which you want authenticated users to be able to access.  You've got nginx running on the front-end server. You're willing to open up a port on the outside firewall, but all access on that port needs to go through your main web-app's permissions. You setup an nginx proxy like so:

upstream internal_gui {
    server 198.51.100.5:443 fail_timeout=0;
}

That sets up your upstream proxy. Here we're connecting to ssl. We then setup a server to listen on a high port (using ssl). It has two locations / and /internal-proxy (which is internal). All incoming connections are passed off to your main app_server proxy with a prefix (/internal/). In your main app server you confirm that the user has the permissions required, and if so you do an accel-redirect to /internal-proxy/<path> from the request.

server {
    listen 60298 ssl;
    server_name yourserver yourserver.example.com;
    ssl_certificate      /etc/nginx/keys/server.crt;
    ssl_certificate_key  /etc/nginx/keys/server.key;
    location /internal-proxy/ {
internal; rewrite ^/internal-proxy/(.*)$ /$1 break; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Nginx-Hosted "Yes"; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Protocol $scheme; proxy_read_timeout 1200s; proxy_send_timeout 1200s; proxy_redirect https://$http_host/ /; proxy_redirect https://$http_host:443/ /; proxy_redirect https://$http_host:60298/ /; proxy_redirect https://$proxy_host/ /; proxy_redirect https://$proxy_host:443/ /; proxy_redirect https://$proxy_host:60298/ /; proxy_redirect http://$http_host/ /; proxy_redirect http://$http_host:80/ /; proxy_redirect http://$proxy_host/ /; proxy_redirect http://$proxy_host:80/ /; proxy_pass https://internal_gui;
break; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Nginx-Hosted "Yes"; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Protocol $scheme; proxy_read_timeout 1200s; proxy_send_timeout 1200s; proxy_redirect off; proxy_pass http://app_server; rewrite ^/(.*)$ /internal/$1 break;
break; } }

Anyway, that seems to work for me, if you have any improvements I'd love to hear about them.

Comments

Comments are closed.

Pingbacks

Pingbacks are closed.