大网数据广告活动
服务器运维问答

Can I use nginx to redirect to a most recent file?

· 52CE 我爱测

I was wondering if it is possible to have nginx rewrite a URL to point to the most recent (last naturally sorted) version of a file? Basically, I have a directory full of revisions of a file, like this: /var/files/file-5.6.10.3.t…

问题原文

原帖链接 · Jared Brandt · CC BY-SA 4.0

I was wondering if it is possible to have nginx rewrite a URL to point to the most recent (last naturally sorted) version of a file? Basically, I have a directory full of revisions of a file, like this:

/var/files/file-5.6.10.3.txt
/var/files/file-5.6.10.12.txt
/var/files/file-5.6.10.20.txt
/var/files/file-5.6.12.1.txt
...

And I would like to rewrite a request for "file.txt" to the most recent version of that file. This is kind of what I want to do:

root /var/files;
rewrite file.txt $(ls -v /var/files | tail -1);

Or a 302 would be good too!

location file.txt {
    return 302 $(ls -v /var/files | tail -1);
}

Please also note that symlinking is not an option :( I would like to have this handled by nginx, or some extension to nginx.

已采纳解答

原帖链接 · Jared Brandt · CC BY-SA 4.0

My solution to this problem eventually turned out to be fcgiwrap. This made sense to me, since I was looking to use a shell command within the nginx configuration.

First, install fcgiwrap:

apt-get install fcgiwrap

Write a shell script to perform any kind of logic you need and save it somewhere that nginx can access:

#!/bin/bash

# Filename: /var/www/script

echo "HTTP/1.1 200 OK"
echo "Content-Length: $( echo "$REQUEST_URI" | wc -c )"
echo

echo "$REQUEST_URI"

Launch an fcgiwrap process:

fcgiwrap -s unix:/run/myfunsocket

And finally, configure nginx to serve the request:

location /subdir {
    fastcgi_param SCRIPT_FILENAME /var/www/script;
    fastcgi_param REQUEST_URI $uri;
    fastcgi_pass unix:/run/myfunsocket;
}

With this strategy, you can catch any type of request with a location block, and have a shell script determine what the output for that URI should be.

More information/examples of nginx/fcgiwrap can be found in the NGINX Documentation.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-02-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。