nuxt-modules / sitemap

Powerfully flexible XML Sitemaps that integrate seamlessly, for Nuxt.
https://nuxtseo.com/sitemap
336 stars 31 forks source link

docs: subdomain routing + sitemap #324

Closed danclarkdev closed 3 months ago

danclarkdev commented 3 months ago

📚 Is your documentation request related to a problem?

Hello! I can see pretty thorough documentation on configuring multiple sitemaps here, but my application is set up with subdomain routing using a similar approach to the one shown here

I'd like to be able to control which sitemaps show up at sitemap.xml dependent on the subdomain I'm using. Is there any way of doing this? e.g. providing a callback to the sitemaps config which has access to the Nuxt instance (where I'm storing subdomain information) and returning a variable object based on that?

I can vary the URLs returned in any given sitemap easily enough by using a URL source with a query string parameter, but as far as I'm aware, it is bad practice to serve sitemaps for different subdomains - see here

For example, my application is set up to accept both foo.mysite.com and bar.mysite.com. The subdomain routing code takes the foo subdomain and adjusts the router so that only routes within pages/foo are available - and the equivalent when on the bar subdomain. When I hit foo.mysite.com/sitemap.xml, I want all of the foo.mysite.com urls to be shown (I think I have a good handle on doing this), but nothing from bar.mysite.com

Please let me know if any more information is required!

🔍 Where should you find it?

Probably https://nuxtseo.com/sitemap/guides/multi-sitemaps

ℹ️ Additional context

No response

harlan-zw commented 3 months ago

Hi, thanks for raising this question, it's an interesting use case.

The easiest way to do this would be to use the sitemap:resolved Nitro hook, something like:

import { defineNitroPlugin } from 'nitropack/runtime/plugin'
import { getRequestHost } from 'h3'

export default defineNitroPlugin((nitroApp) => {
const host = getRequestHost(e, { xForwardedHost: true})
  const subdomain = host.split('.')[0]
  nitroApp.hooks.hook('sitemap:resolved', async (ctx) => {
    ctx.urls = ctx.urls.map(p => {
      if (!p.loc.startsWith(`/${subdomain}`))
      return false
      return p.loc.replace(`/${subdomain}`, '')
    }).filter(Boolean)
  })
})

Let me know if you have any questions/issues with that.