Search code examples
nginxfastcgi

How can I configure nginx and fcgi to call separate executables depending on request-uri


Say I have a directory structure like this:

/index
/contact
/view_post

All three are executables that just output html using something basically like echo-cpp from fcgi examples.

The documentation I've read have just shown how to have one program that then parses the request-uri and calls various sections from that. I want to be able to have each of these as separate programs instead of parsing for a request uri and serving the page based on that.

So if I went to localhost/index the index program would be ran with input to it (post data) and its output would go to nginx to serve up the page.

I'm not sure if fcgi is even the right tool for this, so if something else would work better then that is fine.


Solution

  • You can do it with nginx and fcgi. The simplest way to do this is, by using spawn-fcgi -

    First you will need to setup your nginx.conf. Add the following inside the server {} block -

    location /index {
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
    }
    location /contact {
        fastcgi_pass 127.0.0.1:9001;
        include fastcgi_params;
    }
    location /view_post {
        fastcgi_pass 127.0.0.1:9002;
        include fastcgi_params;
    }
    

    Restart nginx and then run your apps listening same ports as declared in the nginx.conf. Assuming your programs are in ~/bin/ folder -

    ~ $ cd bin
    ~/bin $ spawn-fcgi -p 9000 ./index
    ~/bin $ spawn-fcgi -p 9001 ./contact
    ~/bin $ spawn-fcgi -p 9002 ./view_post
    

    Now the requests to localhost/index will forward to your index program and its output will go back to nginx to serve the pages! And the same for contact and view_post!