Search code examples
lighttpdcanonical-link

Lighttpd - add canonical headers to www pages


This is not the classic redirect www to non-www but rather I would like to add canonical headers to all www requests pointing to the non-www page, for example:

Request for https://www.example.com/index.html => Add canonical header to https://example.com/index.html

I have tried to use the generic redirect but it does not look right and it does not evaluate the %1/$1

$HTTP["host"] =~ "^www\.(.*)$" {
  setenv.add-response-header += ( "Link" => "<https://%1/$1>; rel='canonical'" )
}

Thoughts?


Solution

  • OK so I went with the mod_magnet / Lua route which involved two simple steps.

    1. Edit the lighttpd.conf to add both the mod_magnet module and a conditional for when the requested host has www.
    server.modules = ( mod_magnet, )
    $HTTP["host"] ~= "^www\.(.*)$" {
      magnet.attract-physical-path-to = ( "/path/to/canonical.lua" )
    }
    
    1. Writing the simple canonical.lua file (note that I added a check for www. but this is not required as the file is only executed when the host has it!)
    function string.starts(String,Start)
     return string.sub(String,1,string.len(Start))==Start
    end
    
    if string.starts(lighty.request['Host'], "www.") then
      lighty.header["Link"] = "<https://"..string.sub(lighty.request['Host'],5)..lighty.env["request.uri"]..">;rel=\"canonical\""
    end