Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod_rewrite RewriteCond based on Last-modified? (.htaccess)

I know that we can easily base a RewriteCond on any http request header. But can we check (some of) the response headers that are going to be sent? In particular, the Last-modified one?

I want to rewrite a url only when the Last-modified date is older than 30 minutes and I'm trying to avoid the overhead of delegating that check to a php file every single time a file from that directory is requested.

Thanks in advance!

like image 271
Lea Verou Avatar asked Aug 23 '09 08:08

Lea Verou


People also ask

What is $1 in Apache RewriteRule?

In your rewrite, the ^ signifies the start of the string, the (. *) says to match anything, and the $ signifies the end of the string. So, basically, it's saying grab everything from the start to the end of the string and assign that value to $1.

What is RewriteRule in Apache?

RewriteRule specifies the directive. pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser. substitution is the path to the actual URL, i.e. the path of the file Apache servers. flags are optional parameters that can modify how the rule works.

How do you write rewrite rules in httpd conf?

A rewrite rule can be invoked in httpd. conf or in . htaccess . The path generated by a rewrite rule can include a query string, or can lead to internal sub-processing, external request redirection, or internal proxy throughput.

How does mod rewrite work?

mod_rewrite works through the rules one at a time, processing any rules that match the requested URL. If a rule rewrites the requested URL to a new URL, that new URL is then used from that point onward in the . htaccess file, and might be matched by another RewriteRule further down the file.


1 Answers

No, that’s not possible. But you could use a rewrite map to get that information from a program with less overhead than PHP, maybe a shell script.

Here’s an example bash script:

#!/usr/bin/env bash
while read line; do
    max_age=${line%%:*}
    filename=${line#*:}
    if [[ -f $filename ]]; then
        lm=$(stat -f %m "$filename")
        if [[ $(date +%s)-$lm -le $max_age ]]; then
            echo yes
        else
            echo no
        fi
    else
        echo no
    fi
done

The declaration of the rewrite map needs to be placed in your server or virtual host configuraion file as the program is just started once and then waits for input:

RewriteMap last-modified-within prg:/absolute/file/system/path/to/last-modified-within.sh

And then you can use that rewrite map like this (.htaccess example):

RewriteCond %{last-modified-within:30:%{REQUEST_FILENAME}} =yes
RewriteRule ^foo/bar$ - [L]
RewriteRule ^foo/bar$ script.php [L]
like image 114
Gumbo Avatar answered Oct 15 '22 00:10

Gumbo