nginx: Protected proxied application

Nginx is fantastic for managing things such as personal servers, and proxying various bits and pieces to different places. One of the tasks I’ve wanted to do was to password protect a specific directory with a password, and not to use the crummy old username and password popup. This also allows you to potentially do things such as using OAuth, or other mechanisms.

This requires PHP with sessions installed, and working through nginx.

To protect a location in your nginx config you’ll need something like the following:

location /party { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 604800; proxy_send_timeout 604800; proxy_pass http://127.0.0.1:6680; # This is the important line! auth_request /auth/check_party.php; }

This basically uses the auth_request directive which does a sub-request to my PHP script, for every HTTP request. This even works for websockets (I protected a Mopidy instance using this, the idea being guests can interact with the home stereo easily).

Depending on how your nginx is setup, you’ll need to ensure /auth/check_party.php actually goes somewhere. In my case, this hits an actual PHP file which looks like the following:

<?php session_start(); if($_SESSION['role'] != 'music'){ http_response_code(401); }

This uses standard PHP sessions to authenticate. We have a very stupidly simple check, but this could
be easily expanded to include checking user roles per request etc. However note that debugging these
scripts is quite difficult due to the nature of them!


Share: Twitter icon LinkedIn icon Facebook icon

Joe

I like pushing buttons to make seamless, almost invisible experiences for people. It's a little abstract of a vision, but it's entirely possible.