Blog

How to set up a simple FastCGI server with Cowboy in Erlang for PHP applications?

COW BOY / Erlang / PHP

How to set up a simple FastCGI server with Cowboy in Erlang for PHP applications?

FastCGI is a protocol for communication between a web server and a backend application, and Cowboy is a lightweight Erlang web server.

Here is a basic guide to set up a simple FastCGI server with Cowboy in Erlang for PHP applications:

  1. Install Required Software:

Make sure you have Erlang/OTP installed on your server.
Install Cowboy, which is a small, fast, modern HTTP server.

rebar3 new cowboy my_fastcgi
cd my_fastcgi

2. Configure Cowboy for FastCGI:

Edit the sys.config file to include the FastCGI configuration for Cowboy. Add the following lines to the sys.config file:


{my_fastcgi, [
    {port, 8080},
    {env, [
        {dispatch, [{'_', [{[<<"php">>, <<"*">>], my_fastcgi_handler, []}]}]}
    ]}
]}

This configuration sets up Cowboy to listen on port 8080 and route requests with the path starting with “/php/” to the my_fastcgi_handler module.

3. Implement the FastCGI Handler:

Create a module named my_fastcgi_handler.erl in the src directory. This module will handle FastCGI requests. Here’s a simple example:

init(Req, Opts) ->
    {ok, Req, Opts}.

handle(Req, Opts) ->
    {ok, Req2} = cowboy_req:reply(200, [], <<"Hello, this is a FastCGI handler!">>, Req),
    {ok, Req2, Opts}.

terminate(Reason, Req, Opts) ->
    ok.


4. Compile and Run:

Compile the project and start the Cowboy server:

rebar3 compile
rebar3 shell

The server should be running on5. Configure Your Web Server: http://localhost:8080.

5. Configure Your Web Server:

You need a web server (e.g., Nginx or Apache) to act as a reverse proxy and forward PHP requests to the Erlang FastCGI server.

For Nginx, you can add a configuration like:

location ~ \.php$ {
    proxy_pass http://localhost:8080;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Adjust the configuration based on your environment.

6. Test:

Create a PHP file (e.g., info.php) in the appropriate directory accessible by your web server and test if it works by visiting http://localhost/info.php.

Spread the love

Leave your thought here

Your email address will not be published. Required fields are marked *