在nginx中获取一个自epoch(秒)以来的当前时间字符串

pkmbmrz7  于 7个月前  发布在  Nginx
关注(0)|答案(3)|浏览(91)

在nginx配置文件中,获取一个变量的最佳方法是什么,该变量包含从epoch开始的当前时间(以秒为单位)的字符串表示?从概念上讲,我想要这样的东西:

$timestamp = <unix_time>;
add_header Time $timestamp;

字符串
根据主持人的要求,这不是重复
Is there a way to get the current time in nginx?
因为变量$date_gmt and $date_local不提供seconds-since-epoch格式。

vu8f3i0k

vu8f3i0k1#

根据文档,它在$msec变量中。

643ylb08

643ylb082#

实际上,该功能已添加到此模块中:
https://github.com/openresty/set-misc-nginx-module
搜索的行将是:
第一个月

tkclm6bt

tkclm6bt3#

虽然一个用例是设置一个头,但这个问题是通用的,所以这里有一些关于$msec时间戳的更多用法示例:

日志:

nginx log_format指令可以使用$msec

log_format timed '[$time_local]  '
                    '"$request" $status  $body_bytes_sent B '
                    'at $msec ' ;

字符串
日志格式的结果:

- [01/Nov/2023:18:52:05 +0000]  "GET /favicon.ico HTTP/1.1" 200  870 B at 1698864725.928

返回时间戳的URL:

我的用例是通过http请求服务器时间戳。这个解决方案需要使用echo模块(在我的安装中默认可用)。

load_module modules/ngx_http_echo_module.so;


我的服务器块中的位置块如下:

location /ts {
  default_type 'text/plain';
  echo -n "$msec";
}


获取此路由只会返回时间戳字符串:

> curl https://myserver.com/ts
1698866215.554

相关问题