Screencast
22. XML Sitemaps in Phoenix Applications
Generate XML Sitemaps in Phoenix for SEO
def index(conn, _params) do
conn
|> put_resp_content_type("text/xml")
|> render("index.xml", layout: false, posts: Posts.list_published_posts())
end
Implementing XML sitemaps in Phoenix is straightforward but requires attention to detail. The key is properly configuring your application to handle XML responses and ensuring proper content type headers. This tutorial shows you how to set up a dedicated sitemap controller that dynamically generates an XML sitemap, making your content more discoverable to search engines. You'll learn how to structure your sitemap controller without unnecessary middleware, optimizing it for quick responses to search engine requests.
Dynamic Content in Phoenix XML Sitemaps
<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
<%= for post <- @posts do %>
<url>
<loc><%= url(~p"/posts/#{post.slug}") %></loc>
<lastmod><%= Calendar.strftime(post.updated_at, "%Y-%m-%d") %></lastmod>
</url>
<% end %>
</urlset>
Beyond basic static sitemaps, a robust Phoenix application needs to handle dynamic content. This section demonstrates how to automatically include your database content in your sitemap, ensuring that new posts or updates are immediately reflected for search engines. You'll learn how to properly format URLs and timestamps according to sitemap specifications, and how to use EEx templates effectively for XML generation. This approach keeps your sitemap automatically synchronized with your content without manual intervention.