Skip to content
Advertisement

Serve file from cache folder if it exists, otherwise rewrite to “index.php” using .htaccess

Suppose in root directory I have one file (called index.php) and one folder (called caches). I want that if the file exist in caches folder serve that file (caches/xxx.html) otherwise request send to index.php.

For example I will send request to server: https://example.com/how-to-do and Apache search first in cache/. If how-to-do.html exists then send (rewrite Apache) how-to-do.html otherwise send request to index.php.

This my .htaccess:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Advertisement

Answer

Immediately before your last rule (ie. before the # Send Requests To Front Controller... comment) you can add something like the following:

# Check if cache file exists and serve from cache if it is
RewriteCond %{DOCUMENT_ROOT}/cache/$0.html -f
RewriteRule ^[^/.]+$ cache/$0.html [L]

This only checks for requests that target the document root, eg. /how-to-do – as in your example. It also assumes that your URL-path does not contain a dot (used to delimit file extensions). It does not target requests with multiple path segments, eg. /foo/bar.

To match multiple path segments then simply remove the slash from the regex character class. ie. ^[^.]+$.

The RewriteRule pattern ^[^/.]+$ matches any non-empty URL-path that does not contain the characters slash and dot. In other words it matches URL-paths that consist of a single path segment, excluding files (that naturally include a dot before the file extension). In .htaccess, the URL-path that is matched by the RewriteRule pattern does not start with a slash.

$0 is a backreference that contains the entire URL-path that is matched by the RewriteRule pattern (ie. ^[^/.]+$).


Reference

The official Apache docs should be your go to reference for this (although the docs are rather concise and somewhat lacking examples in places):

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement