Skip to content

Commit

Permalink
Merge pull request #4241 from alphagov/handle-favicon
Browse files Browse the repository at this point in the history
Handle root favicon requests
  • Loading branch information
KludgeKML authored Sep 25, 2024
2 parents a22c30e + 1b3ac8e commit bca270f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions app/controllers/favicon_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Because favicon has to be present at root, we need a controller
# to redirect it to the asset. When there's a better solution to this
# problem we can remove this controller and routes.
class FaviconController < ApplicationController
before_action { expires_in(1.day, public: true) }

def redirect_to_asset
redirect_to(view_context.asset_path("favicon.ico"),
status: :moved_permanently,
allow_other_host: true)
end
end
3 changes: 3 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
# http://stackoverflow.com/a/3443678
get "*path.gif", to: proc { |_env| [404, {}, ["Not Found"]] }

# Favicon redirect
get "/favicon.ico", to: "favicon#redirect_to_asset"

unless Rails.env.production?
get "/development", to: "development#index"
end
Expand Down
Empty file removed public/favicon.ico
Empty file.
9 changes: 9 additions & 0 deletions spec/requests/favicon_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
RSpec.describe "Favicon" do
it "redirects permanently to an asset with a 1 day expiry" do
get "/favicon.ico"

expect(response.headers["Cache-Control"]).to eq("max-age=86400, public")
expect(response.status).to eq(301)
expect(response.location).to match(/http:\/\/www.example.com\/assets\/frontend\/favicon-(.+).ico/)
end
end

0 comments on commit bca270f

Please sign in to comment.