j_d
j_d

Reputation: 3082

How to redirect based on date with nginx?

So, a client is running a promo at a url, where each successive day the url must be a different webpage. All the webpages are already existing, it just means we must put a temporary redirect on this url each day. To avoid having to do this manually each day, I am wondering if this kind of date conditional redirect is possible with nginx.

Here's what the route looks like now:

location /10-day-promo {
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_read_timeout 300;
    proxy_pass      http://50.160.80.120:8000;
}

I need something like:

location /10-day-promo {
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_read_timeout 300;

    if right_now >= start_date and right_now <= end_date then
      return proxy_pass      http://50.160.80.120:8000;
    end
}

I'm not too familiar with nginx syntax so it is just an example. Is this type of thing possible?

Upvotes: 2

Views: 3511

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

nginx has a datetime variable and a regular expression engine, so it is certainly possible, just not very pretty if your datetime boundaries are in awkward places.

For example, 5th November to 14th November UTC inclusive could be represented as:

if ($time_iso8601 ~ ^2017-11-(0[5-9]|1[0-4]) ) { ... }

As an alternative, consider placing the regular expressions into a map. See this document for more. Also, there are language extensions available, e.g. Perl or Lua.

Upvotes: 1

Related Questions