Home > Software design >  Serve file from cache folder if it exists, otherwise rewrite to "index.php" using .htacces
Serve file from cache folder if it exists, otherwise rewrite to "index.php" using .htacces

Time:03-16

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>

CodePudding user response:

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 does not target requests with multiple path segments, eg. /foo/bar.

  • Related