我有一个 Strapi (v4) 后端和一个 Nuxt (v2) 前端,所有内容都是使用 REST 和 GraphQL 获取的。每个环境运行在不同的服务器和域上(提供商是 Digital Ocean)
我的客户想要使用 Strapi 管理应用于前端的 301 重定向列表(包括正则表达式)。
因此,当 Strapi 在
www.site.com/old-url
上运行时,访客可以从
www.site.com/new-url
重定向到
backend.site.com
我不知道如何解决这个问题。我目前正在 Nuxt 中使用中间件进行重定向,但是我可以使用 ajax 从 Strapi 获取重定向列表吗?这会减慢每个请求的速度。我可以制作某种脚本来从 Strapi 获取重定向并将其保存到中间件可以使用的 JSON 文件吗?这可能可行,但似乎不太优雅。
有我忽略的更好的解决方案吗?
这对我使用 Strapi CMS v5 和 NextJs v13 很有帮助,我猜用 Nuxt 也可以制作类似的东西
(https://www.npmjs.com/package/strapi-plugin-redirects)
创建redirects.js
const getRedirects = async () => {
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_API}/redirects`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.redirects.map(({ from, to, type }) => ({
source: from.startsWith('/') ? from : `/${from}`,
destination: to,
permanent: type === 'moved_permanently_301',
}));
} catch (error) {
console.error('Failed to fetch redirects:', error);
return [];
}
};
module.exports = getRedirects;
添加
const getRedirects = require('./lib/redirects');
...
async redirects() {
return await getRedirects();
}
到 next.config.js
/** @type {import('next').NextConfig} */
const getRedirects = require('./lib/redirects');
const nextConfig = {
reactStrictMode: true, //React StrictMode renders components twice on dev server
swcMinify: true,
optimizeFonts: true,
compress: true,
images: {
remotePatterns: [
{
protocol: "https",
hostname: "res.cloudinary.com",
},
],
minimumCacheTTL: 1500000,
},
experimental: {
fontLoaders: [{ loader: "@next/font/google" }],
},
async redirects() {
return await getRedirects();
}
};
module.exports = nextConfig;