Selaa lähdekoodia

Add a method for generating a link to a static file

+ add caching of static files with resetting browser cache via filename.
Visman 4 vuotta sitten
vanhempi
commit
35c94a2550
3 muutettua tiedostoa jossa 50 lisäystä ja 1 poistoa
  1. 15 0
      .dist.htaccess
  2. 20 1
      app/Models/Page.php
  3. 15 0
      public/.dist.htaccess

+ 15 - 0
.dist.htaccess

@@ -13,8 +13,23 @@ AddDefaultCharset UTF-8
 
   RewriteRule !^public/ index.php [L]
 
+  RewriteCond %{REQUEST_URI} \.v\.[0-9]
+  RewriteRule ^(.+)\.v\.[0-9]+\.([^.\\/]++)$ $1.$2 [L]
+
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^public/ index.php [L]
 
   RewriteRule \.dist\. index.php [L]
 </IfModule>
+
+<IfModule mod_expires.c>
+  ExpiresActive on
+
+  ExpiresByType text/css A31536000
+  ExpiresByType application/javascript A31536000
+
+  ExpiresByType image/gif A31536000
+  ExpiresByType image/png A31536000
+  ExpiresByType image/jpg A31536000
+  ExpiresByType image/jpeg A31536000
+</IfModule>

+ 20 - 1
app/Models/Page.php

@@ -61,7 +61,7 @@ abstract class Page extends Model
         $this->pageHeader('mainStyle', 'link', [
             'rel'  => 'stylesheet',
             'type' => 'text/css',
-            'href' => $this->c->PUBLIC_URL . '/style/' . $this->user->style . '/style.css',
+            'href' => $this->publicLink("/style/{$this->user->style}/style.css"),
         ]);
 
         $now = \gmdate('D, d M Y H:i:s') . ' GMT';
@@ -468,4 +468,23 @@ abstract class Page extends Model
 
         return \array_reverse($result);
     }
+
+    /**
+     * Возвращает url для $path заданного в каталоге public
+     * Ведущий слеш обязателен O_o
+     */
+    public function publicLink(string $path): string
+    {
+        $fullPath = $this->c->DIR_PUBLIC . $path;
+
+        if (\is_file($fullPath)) {
+            $time = \filemtime($fullPath) ?: '0';
+
+            if (\preg_match('%^(.+)\.([^.\\/]++)$%D', $path, $matches)) {
+                return $this->c->PUBLIC_URL . "{$matches[1]}.v.{$time}.{$matches[2]}";
+            }
+        }
+
+        return $this->c->PUBLIC_URL . $path;
+    }
 }

+ 15 - 0
public/.dist.htaccess

@@ -16,4 +16,19 @@ AddDefaultCharset UTF-8
   RewriteRule . index.php [L]
 
   RewriteRule \.dist\. index.php [L]
+
+  RewriteCond %{REQUEST_URI} \.v\.[0-9]
+  RewriteRule ^(.+)\.v\.[0-9]+\.([^.\\/]++)$ $1.$2 [L]
+</IfModule>
+
+<IfModule mod_expires.c>
+  ExpiresActive on
+
+  ExpiresByType text/css A31536000
+  ExpiresByType application/javascript A31536000
+
+  ExpiresByType image/gif A31536000
+  ExpiresByType image/png A31536000
+  ExpiresByType image/jpg A31536000
+  ExpiresByType image/jpeg A31536000
 </IfModule>