Is possible to intercept a request for a nonexistent file with lighttpd?
Is it possible to configure lighttpd so that a request for a file succeeds if the file exists, but is handled and redirected, for example to a cgi script, if the file does not exist?
What I'm trying to achieve is having a set of image files on disk which are generated by a script and served directly. On a request, if the file does not exist, the script will generate the image and save it to disk (for future requests) and then either serve the image directly or redirect back to t开发者_如何学JAVAhe same URL which will this time succeed. I'm essentially caching the generated output on disk.
I currently have a prototype in which the script always handles the request, reading and echoing the file if it exists, but I'd rather save the overhead and have lighttpd serve it directly if possible.
You can have the best of both worlds. Lighttpd will serve the file if you give it a
X-Sendfile: path to file
see: http://redmine.lighttpd.net/wiki/1/X-LIGHTTPD-send-file. There's a php example on the documentation page.
You can set the:
server.error-handler-404
config option to a script which will do what you want.
see http://redmine.lighttpd.net/wiki/1/Server.error-handler-404Details
This question may be old, but it asked exactly what I wanted an answer to. Here is the solution that I came up with...
Here is a complete, and minimal, working configuration file for Lighttpd.
server.document-root = "/srv/http"
server.port = 80
server.username = "nobody"
server.groupname = "nobody"
server.dir-listing = "enable"
server.stream-response-body = 2
server.modules = (
"mod_rewrite",
"mod_alias",
"mod_cgi"
)
url.rewrite-if-not-file = ( "^/alpine/.*\.apk$" => "/fecher" )
alias.url += ( "/fecher" => "/bin/fecher" )
$HTTP["url"] =~ "^/fecher$" {
cgi.assign = ( "" => "" )
}
This sits on a server where I store package files. It directly serves any files it has and requests for anything it doesn't are delegated to a CGI script called /bin/fecher
.
- The
url.rewrite-if-not-file
rewrites any URL matching the given regex to/fecher
. - the URL
/fecher
is aliased (changing its document root) to/bin/fecher
. - CGI is enabled for URLs matching the regex
^/fecher$
(i.e. only/fecher
). - the server.stream-response-body setting prevents Lighttpd buffering the CGI output into a temporary file (I did not want to provide it with write access to
/var/tmp
or anywhere else).
If the server encounters a URL matching the first expression for which it lacks the file, the URL gets rewritten and mapped to the CGI script which is executed.
On my server /bin/fecher
is a shell script that pulls the missing package from upstream, returns it to the client and stores it locally for future requests.
精彩评论