feat: add default canonical URL handling
Some checks failed
Docker Dev / docker (push) Has been cancelled
CI / scan_ruby (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / test (push) Has been cancelled
Docker Main / docker (push) Has been cancelled

- Introduce a new before_action to set the default canonical URL
- Implement set_canonical_url method to manage canonical URLs
- Update application helper to use the canonical URL for meta tags

This change enhances SEO by ensuring that the canonical URL is set
correctly for each page, preventing duplicate content issues. The
canonical URL is derived from the original request URL, excluding
query parameters.
This commit is contained in:
songtianlun 2025-04-23 20:45:49 +08:00
parent 81c1d33036
commit 07afbda252
2 changed files with 10 additions and 0 deletions

View File

@ -3,6 +3,7 @@ class ApplicationController < ActionController::Base
# Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
before_action :log_browser_info before_action :log_browser_info
before_action :set_content_type_for_rss, if: -> { request.format.rss? } before_action :set_content_type_for_rss, if: -> { request.format.rss? }
before_action :set_default_canonical_url
# allow_browser versions: :modern # allow_browser versions: :modern
# allow_browser versions: :modern, # allow_browser versions: :modern,
# patterns: [ # patterns: [
@ -74,6 +75,10 @@ class ApplicationController < ActionController::Base
end end
end end
def set_canonical_url(url = nil)
@canonical_url = url || request.original_url.split("?").first
end
private private
def set_locale(&action) def set_locale(&action)
@ -127,4 +132,8 @@ class ApplicationController < ActionController::Base
def set_content_type_for_rss def set_content_type_for_rss
response.headers["Content-Type"] = "application/rss+xml; charset=utf-8" response.headers["Content-Type"] = "application/rss+xml; charset=utf-8"
end end
def set_default_canonical_url
@canonical_url = request.original_url.split("?").first
end
end end

View File

@ -34,6 +34,7 @@ module ApplicationHelper
keywords: t("meta.default.keywords", default: "AI weather art, weather visualization, city weather, artificial intelligence"), keywords: t("meta.default.keywords", default: "AI weather art, weather visualization, city weather, artificial intelligence"),
separator: "&mdash;".html_safe, separator: "&mdash;".html_safe,
reverse: true, reverse: true,
canonical: @canonical_url,
og: { og: {
site_name: t("site_name", default: "TodayAIWeather"), site_name: t("site_name", default: "TodayAIWeather"),
type: "website", type: "website",