オマエラ wlog

← go back

Gallery (gal) and CGI on nginx

by z411 @ 2016-08-10 [ meta ]

So I installed 4x13's py-gal, a minimalist script inspired by gelbooru community-contributed image galleries. It's simple CGI (Python) and works well so far, might as well use it to archive trash I have scattered on old hard drives.

Running FastCGI

By the way, nginx is nice. And I mean nice. The way it handles FastCGI is transparent, configuration is simple and the way it works as a proxy makes it pretty clean. For example, a simple FastCGI script (ran as proper FastCGI) would work like this in Python with the flup FCGI module:

#!/usr/bin/env python
import os
from flup.server.fcgi import WSGIServer

def myapp(environ, start_response):
  start_response('200 OK', [('Content-Type', 'text/plain')])
  return ['sup.\n']

if __name__ == '__main__':
  from fcgi import WSGIServer
  WSGIServer(myapp, bindAddress='/tmp/test.sock').run()

Then we just run the script manually; it will run as a server, and create the /tmp/test.sock file. Make sure it's readable by nginx's user. Indeed, your script will act as a FastCGI server, and nginx will communicate with it through the Unix socket.

Then in nginx site configuration we add something like:

location /cgi-bin/myapp.py {
  include /etc/nginx/fastcgi_params;
  fastcgi_pass unix:/tmp/test.sock;
}

We try to load this URL in our browser, and it should communicate with the FastCGI script and return its output, "'sup."

Running normal CGI

Now, the problem is that nginx can only talk to FastCGI servers, but you might want to run normal CGI scripts i.e. non-FastCGI. nginx has got you covered now as there's a simple wrapper around normal CGI scripts called fcgiwrap. This is basically a FastCGI server in itself that runs normal CGI scripts and returns their output to nginx. You can see it as a middle-man.

Using it is as simple as adding something like this in your site configuration:

location ~ \.py$ {
  include /etc/nginx/fastcgi_params;
  fastcgi_pass unix:/var/run/fcgiwrap.socket; # or wherever the socket is located
}

This way you should be able to run any Python CGI script anywhere. Of course this should also work with Perl or any other CGI script. For PHP you might want to take a look at php-fpm (FastCGI wrapper for PHP), as PHP isn't normal CGI like Perl or Python.

Tweet | Permalink | 17:06