Search code examples
c++nginxcgifastcginginx-location

How to run c++ CGI script on NGINX server


I have written below lines in configuration file created in /etc/nginx/conf.d named as "helloworld.local.conf".

server{
     listen 80 default_server;
     server_name hello_world;
     location / {
          root /var/www/helloworld;
          fastcgi_pass 127.0.0.1:9000;
     } 
}

There is an index.html file in /var/www/helloworld which is displaying text "site comming soon".

My c++ code looks like below:

#include <iostream>
#include "fcgio.h"

using namespace std;

int main(void) {
    cout<<"Content-type:text/html\r\n\r\n";
    cout<<"<html>\n";
    cout<<"<head>\n";
    cout<<"<title>Hello World- First CGI Program</title>\n";
    cout<<"</head>\n";
    cout<<"<body>\n";
    cout<<"<h2> hello world</h2>\n";
    cout<<"</body>\n";
    cout<<"</html>\n";
    return 0;
}

I have the c++ binary code file is produced using the following command

g++ abc.cpp -lfcgi++ -lfcgi -o hello_world

which is needed to be deployed on the NGINX server. I searched and tried different ways to run this script on the stackoverflow but still missing something.

I also ran the below command to connect c++ binary code file to server

cgi-fcgi -start -connect 127.0.0.1:9000 ./hello_world

Now when i am visiting the address 127.0.0.1:9000 in the browser, not getting "hello world " text which is in the c++ code.

Output: I am suppose to get response as "hello world" from the the c++ binary code and that to be displayed on the html page.

What am i missing please help.

UPDATE: this is my config file now.

server{
    server_name hello;
    location / {
        fastcgi_index index.cgi;
        root /var/www/helloworld;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_name;
        include fastcgi_params;
    }
}

Solution

  • UPDATE

    Take a look at this blog post. It explains how to setup C++/FCGI/nginx quite thoroughly.


    ORIGINAL ANSWER

    Your C++ code should be a listener (when it's running, it should listen to a port and return responses upon incoming requests). This part doesn't have anything to do with nginx. So first make sure that your code is working correctly; Run your code and try to access the specified port and see if you get the expected response.

    Then you need to setup a proxy in your nginx configuration that basically redirects all of the traffic that you want to your C++ port (e.g 9000). For example you can set it up so that any url in the form of https://your_domain.com/api/* redirects to your C++.

    This is pretty easy in nginx:

    location /api/ {
        proxy_pass  http://127.0.0.1:9000/;
    }
    

    But first test your C++ alone, and make sure it works fine

    Also you'd better use something like runit, systemd, or similar tools to keep your C++ listener running (restart it if it crashes).