Kensuke Kousaka's Blog

Notes for Developing Software, Service.

Note about how to run CGI on nginx

Note about how to configure nginx to work with CGI written in Python.

Introduce fcgiwrap

To work ordinaly CGI on nginx, install fcgiwrap by running following command.

# pacman -S fcgiwrap

After installing, run following command to copy fcgiwrap.service under /usr/lib/systemd/system/ to /etc/systemd/system/.

# cp /usr/lib/systemd/system/fcgiwrap.service /etc/systemd/system/fcgiwrap.service

After copying, edit /etc/systemd/system/fcgiwrap.service by following.

[Unit]
Description=Simple CGI Server
After=nss-user-lookup.target fcgiwrap.socket

[Service]
Sockets=fcgiwrap.socket
ExecStart=/usr/sbin/fcgiwrap -c 4
User=http
Group=http

[Install]
Also=fcgiwrap.socket

After editing, run following commands to start service and auto start when system startup.

# systemctl start fcgiwrap.service
# systemctl enable fcgiwrap.service

Configure nginx

Next, configure nginx. Add like following to server block in nginx configuration file.

location /cgi/ {
    root /YOUR/DOCUMENT/ROOT/HERE;
    fastcgi_pass unix:/run/fcgiwrap.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /YOUR/DOCUMENT/ROOT/HERE$fastcgi_script_name;
}

Write CGI directory name after location. If you want to put CGI directory cgi under document root, configuration is like above.

After configurating above, run following command to reload nginx.

# systemctl reload nginx

Now, all configurations have been completed. Put your CGI program to your configured path and grant execution authority, then probably execute CGI on nginx.