Nginx - Run command on HTTP request

Viewed 147

How can I run a command like shutdown when my Nginx receives an HTTP request?

I read about writing modules for this, but I find it overkilling, I just need to shutdown the computer when an HTTP request is answered.

1 Answers

There is an impressively creative solution to implement some kind of shell webhooks I found recently on GitHub (all credits goes to the author).

It consist of three parts.

  • A systemd unit to run a socat utility listening the loopback network interface (don't open used TCP port to the outer world in any case!):
[Unit]
Description=socat-based cmd api
After=network.target

[Service]
User=nobody
Group=nobody
ExecStart=/usr/bin/socat UDP-LISTEN:50333,fork,bind=127.0.0.1 EXEC:/opt/bin/shell-webhook
Restart=always

[Install]
WantedBy=multi-user.target
  • A shell script to be placed somewhere (the above unit assumes it to be the /opt/bin/shell-webhook):
#!/bin/bash

LOG=/var/log/shell-webhook.log

declare -a DATA
read -a DATA 
cmd=${DATA[4]}

case ${cmd} in

  reboot)
    echo "Executing reboot" >> ${LOG}
    shutdown -r now
    ;; 

  shutdown)
    echo "Executing shutdown" >> ${LOG}
    shutdown -P now
    ;;

  *)
    echo "Unknown command $cmd" >>  ${LOG}
    ;;

esac
  • An nginx-relevant configuration part (consider preventing access to this location using some kind of access control - allow/deny rules, basic auth, etc.):
log_format shellwebhook '$cmd\n';

server {
    ...
    location ~* ^/cmd/(\w+)$ {
        set $cmd $1;
        return 200 "$cmd";
        access_log syslog:server=127.0.0.1:50333,facility=local7,tag=nginx,severity=info,nohostname shellwebhook;
    }
}
Related