authenticated static file serving with nginx

alex 14th May 2024 at 9:35am

Now, my goal is to have authenticated file serving with nginx. I learned about the X-Accel request header; from the documentation,

This allows you to handle authentication, logging or whatever else you please in your backend and then have NGINX handle serving the contents from redirected location to the end user, thus freeing up the backend to handle other requests. This feature is commonly known as X-Sendfile.

which is exactly what I need! If a given user meets the very strict security requirements, then this happens:

class StintProtectedFilesView(StudentCodeRequiredMixin, View):
    def get(self, request, student_code: str, stint_code: str,
				[..]
	 			response = HttpResponse()
    		response['X-Accel-Redirect'] = f'/protected/{filepath}'
        return response

And the whole process is then handled by nginx. Of course, this doesn't seem like much, yes? I asked Phind what stops anyone from handcrafting a request with X-Accel-Redirect as a header?, and it provided a very convincing response that I checked against nginx's own documentation; in essence, nginx ignores client requests with this header, and it only uses it for internal redirections; and I'm happy with that as long as it works. For good measure, I looked x-accel nginx security issues up on DuckDuckGo: and there's nothing. I'm satisfied.

Now it is only a matter of hooking up the protected view to nginx.