wick
wick

Reputation: 2234

Get a string of current time since epoch (seconds) in nginx

In nginx configuration file, what is the best way to get a variable containing string representation of current time in seconds since epoch? Conceptually I want something like this:

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

As requested by a moderator, this is not a duplication of

Is there a way to get the current time in nginx?

as variables $date_gmt and $date_local do not provide seconds-since-epoch format.

Upvotes: 3

Views: 4133

Answers (3)

Jeff Ward
Jeff Ward

Reputation: 19136

While one use case is setting a header, the question is generic, so here are some more usage examples for the $msec timestamp:

Logging:

The nginx log_format directive can use $msec:

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

Results in logs of the format:

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

URL that returns the timestamp:

My use case was requesting the server timestamp via http. This solution requires the use of the echo module (was available by default in my installation.)

load_module modules/ngx_http_echo_module.so;

The location block inside my server block was as follows:

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

Fetching this route simply returns the timestamp string:

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

UPD If you don't have the ping module:

location /ts {
  return 200 "$msec";
}

Upvotes: 0

wick
wick

Reputation: 2234

In fact, the functionality was added to this module:

https://github.com/openresty/set-misc-nginx-module

Sought line would be:

set_formatted_gmt_time $unix_time_str "%s";

Upvotes: 2

miknik
miknik

Reputation: 5951

As per the docs, it's in the $msec variable.

Upvotes: 5

Related Questions