How to run some code or command in apache on condition?

Viewed 137

I have a use case, where I need to execute some script or execute a Linux command if a specific condition is met in an HTTP request. I am checking if any DELETE method request comes to my httpd server, I want to do some work like backing up files. I am not sure how to do that with the Apache web server. But I am aware about the if module in Apache:

<If "%{REQUEST_METHOD} = DELETE">
    # execute script or Linux command
</If>

Is it possible with Apache? Can it be achieved in any other web server?

1 Answers

You can internally rewrite the request to a server-side script (PHP, CGI, etc.) conditionally based on an element of the request using mod_rewrite on Apache. You do not need to use an <If> expression for this.

For example, to internally rewrite any DELETE request to your script /scripts/script-to-run.cgi then you could use the following:

RewriteEngine On

RewriteCond %{REQUEST_METHOD} =DELETE
RewriteRule !^/?scripts/ scripts/script-to-run.cgi [L]

The RewriteRule pattern !^/?scripts/ simply makes sure the script is not called for requests to the /scripts/ directory itself (to avoid a rewrite loop).

<If "%{REQUEST_METHOD} = DELETE">

This is not syntactically valid. You need to surround the string argument (RHS of the expression) in single quotes. The = operator is permitted, although it's preferable to use the full form == to avoid confusion and be similar with other languages.

For example:

<If "%{REQUEST_METHOD} == 'DELETE'">

Further reading:

Related