How to Setup Caching on Lighttpd

A comprehensive guide to configuring caching and compression in Lighttpd for optimal performance.

Prerequisites

Before configuring caching on Lighttpd, ensure you have:

  • Lighttpd installed and running
  • Access to lighttpd.conf
  • Basic understanding of HTTP caching concepts
  • Root or sudo access to the server

Basic Caching Configuration

Cache Configuration
server.modules += ( "mod_expire" )

$HTTP["url"] =~ "\.(jpg|jpeg|png|gif|ico|css|js)$" {
    expire.url = ( "" => "access plus 1 years" )
}

$HTTP["url"] =~ "\.(html|htm)$" {
    expire.url = ( "" => "access plus 1 hours" )
}

# Enable mod_compress
server.modules += ( "mod_compress" )
compress.cache-dir = "/var/cache/lighttpd/compress/"
compress.filetype = (
    "text/plain",
    "text/html",
    "text/css",
    "text/javascript",
    "application/javascript"
)

Key directives explained:

  • mod_expire: Module for cache control
  • expire.url: Sets expiration time for matched URLs
  • mod_compress: Enables compression

Cache-Control Headers

Advanced Cache Control
server.modules += ( "mod_setenv" )

# Static assets with long cache
$HTTP["url"] =~ "\.(css|js|jpg|jpeg|png|gif)$" {
    setenv.add-response-header = (
        "Cache-Control" => "public, max-age=31536000, immutable"
    )
}

# Dynamic content with no cache
$HTTP["url"] =~ "^/(api|admin)/" {
    setenv.add-response-header = (
        "Cache-Control" => "no-store, no-cache, must-revalidate",
        "Pragma" => "no-cache"
    )
}

Compression Settings

server.modules += ( "mod_compress" )

compress.cache-dir = "/var/cache/lighttpd/compress/"
compress.filetype = (
    "text/plain",
    "text/html",
    "text/css",
    "text/javascript",
    "application/javascript",
    "application/json",
    "application/xml",
    "image/svg+xml"
)

compress.allowed-encodings = ("gzip", "deflate")
compress.max-filesize = 1048576

Compression settings explained:

  • cache-dir: Directory for compressed files
  • filetype: File types to compress
  • max-filesize: Maximum file size for compression

Configuration Generator

Generated Configuration
# Lighttpd configuration will appear here

Best Practices

Recommended Practices
  • Static Assets:
    • Use long cache times (1 year) with versioned URLs
    • Add Cache-Control: public for CDN caching
    • Enable compression for text-based assets
  • Dynamic Content:
    • Use shorter cache times
    • Implement cache busting for updates
    • Consider using no-cache for user-specific content
  • API Responses:
    • Use no-store for sensitive data
    • Implement ETag headers for validation
    • Consider using Vary header for different responses