Caching all php output to static html using htaccess and modrewrite

I have a Php site which on some page already creates the entire cache output file, although it is not saved as .htmlit is still sent from Php upon request, it skips the hosting cache for static files that have very good performances.

Cache files are stored in a directory based on md5(Url).

I wonder if it can mod_rewriteget a similar result, but with html static files, I think I saw something similar once with the WordPress cache plugin (but at that time I didn’t pay much attention).

What can I use instead of md5()with mod_rewriteto convert the entire URL to a valid unique file name?

My Url is virtual routes and very simple: /level1/level2/level3/(this work is still ongoing, but I do not think that using more than three levels levelN, obviously, is an example, maybe any word)

To simplify, I would like to:

mod_rewrite: / cache / unique (Url) .html exist? Download it

php: / cache / unique (Url) .html doesn't exist? Create it

What can i use for unique?

+4
source share
2 answers

Yes, you can do this, I will not offer all the code, just an idea will be sufficient.

.htaccess
.htaccess , . .

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Request to index.php, .

, .

" ".

index.php
, , . include. . 5 .

.

$levels = explode('/',<REQUESTED_URI>);
$filename = array_pop($levels);
foreach($levels as $level)
   // Create Directory if does not exit

, , .

+3

, , Url, WordPress, , - , mod_rewrite .

Url .htaccess mod_rewrite , ( md5 RewriteMap prg, ).

.htaccess , :

RewriteCond %{DOCUMENT_ROOT}/cache/$1/index.html -f
RewriteRule ^(.*) /cache/$1/index.html [L]

Php, CodeIgniter, Php, , ob_start ob_get_clean:

private function cache_output() {
    $this->load->helper('url');
    $uri = uri_string(); /* expect something like: level1/level2 (no heading/trailing slash */ 
    $dir = FCPATH.'cache'.DIRECTORY_SEPARATOR.str_replace('/',DIRECTORY_SEPARATOR,$uri);
    $file = $dir.DIRECTORY_SEPARATOR.'index.html';
    if (!file_exists($file)) {
        if (!is_dir($dir)) {
            mkdir($dir, 0755 & ~umask(), TRUE);
        }
        $output = $this->output->get_output();
        file_put_contents($file, $output);
        chmod($file, 0644 & ~umask());
    }
}
+1

All Articles