nginx - How to run a shell script on every request? nginx - How to run a shell script on every request? nginx nginx

nginx - How to run a shell script on every request?


You can execute a shell script via Lua code from the nginx.conf file to achieve this. You need to have the HttpLuaModule to be able to do this.

Here's an example to do this.

location /my-website {  content_by_lua_block {    os.execute("/bin/myShellScript.sh")  } }


I found the following information online at this address: https://www.ruby-forum.com/topic/2960191

This does expect that you have fcgiwrap installed on the machine. It is really as simple as:

sudo apt-get install fcgiwrap

Example script (Must be executable)

#!/bin/sh# -*- coding: utf-8 -*-NAME=`"cpuinfo"`echo "Content-type:text/html\r\n"echo "<html><head>"echo "<title>$NAME</title>"echo '<meta name="description" content="'$NAME'">'echo '<meta name="keywords" content="'$NAME'">'echo '<meta http-equiv="Content-type"content="text/html;charset=UTF-8">'echo '<meta name="ROBOTS" content="noindex">'echo "</head><body><pre>"dateecho "\nuname -a"uname -aecho "\ncpuinfo"cat /proc/cpuinfoecho "</pre></body></html>"

Also using this as an include file, not restricted to only shellscripts.

location ~ (\.cgi|\.py|\.sh|\.pl|\.lua)$ {    gzip off;    root /var/www/$server_name;    autoindex on;    fastcgi_pass unix:/var/run/fcgiwrap.socket;    include /etc/nginx/fastcgi_params;    fastcgi_param DOCUMENT_ROOT /var/www/$server_name;    fastcgi_param SCRIPT_FILENAME /var/www/$server_name$fastcgi_script_name;}

I found it extremely helpful for what I am working on, I hope it help you out with your RaspberryPI project.


  1. Install OpenResty (OpenResty is just an enhanced version of Nginx by means of addon modules ) Refer https://openresty.org/en/getting-started.html for this
  2. Configure aws cli on the instance
  3. Write a shell script which download a file from specified S3 bucket
  4. Do the required changes in nginx.conf file
  5. Restart the nginx server

I have tested the http request using curl and file gets download in /tmp directory of respective instance:

curl -I http://localhost:8080/

OutPut:

curl -I http://localhost:8080/HTTP/1.1 200 OKServer: openresty/1.13.6.2Date: Tue, 14 Aug 2018 07:34:49 GMTContent-Type: text/plainConnection: keep-alive 

Content of nginx.conf file:

worker_processes  1;error_log logs/error.log;events {    worker_connections 1024;}http {    server {        listen 8080;        location / {           default_type text/html;           content_by_lua '                ngx.say("<p>hello, world</p>")           ';        }        location / {            content_by_lua_block{            os.execute("sh /tmp/s3.sh")            }        }    }}