next.config.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import type { NextConfig } from "next";
  2. import createNextIntlPlugin from "next-intl/plugin";
  3. /** 开发时代理真实后端,避免浏览器直连局域网 IP 时的 CORS。与 .env.development 中 API_PROXY_TARGET 一致。 */
  4. const apiProxyTarget =
  5. process.env.API_PROXY_TARGET?.replace(/\/$/, "") ?? "";
  6. const remittanceProxyTarget =
  7. process.env.API_PROXY_TARGET_REMITTANCE?.replace(/\/$/, "") ?? "";
  8. const nextConfig: NextConfig = {
  9. /**
  10. * 放在 Nginx/Caddy 等反代后面时开启:用客户端的 Host / 转发头构造 URL,
  11. * 避免 Next 把内部监听端口(如 `next start` 默认的 3000)写进重定向,
  12. * 否则浏览器会跳到 `jinclab.com:3000` 且公网 3000 通常不可达。
  13. * 反代需传:`Host`、`X-Forwarded-Proto`(及按需 `X-Forwarded-Host`),且不要把上游端口写进 Host。
  14. */
  15. // Next 16 类型里未声明,运行时仍读取(见 node_modules/next/.../resolve-routes.js)
  16. experimental: {
  17. trustHostHeader: true,
  18. } as NextConfig["experimental"],
  19. /**
  20. * 必须在配置层做根路径重定向:`app/page.tsx` + permanentRedirect 会被预渲染为静态 ○ /,
  21. * 线上容易出现「必须手输 /zh」;redirects 在路由层优先匹配,且 destination 为相对路径,不会错写成 :3000。
  22. */
  23. async redirects() {
  24. return [
  25. {
  26. source: "/",
  27. destination: "/zh",
  28. permanent: true,
  29. },
  30. ];
  31. },
  32. async rewrites() {
  33. const rewrites = [];
  34. if (apiProxyTarget && /^https?:\/\//i.test(apiProxyTarget)) {
  35. rewrites.push({
  36. source: "/api-backend/:path*",
  37. destination: `${apiProxyTarget}/:path*`,
  38. });
  39. }
  40. if (remittanceProxyTarget && /^https?:\/\//i.test(remittanceProxyTarget)) {
  41. rewrites.push({
  42. source: "/api-backend-remittance/:path*",
  43. destination: `${remittanceProxyTarget}/:path*`,
  44. });
  45. }
  46. return rewrites;
  47. },
  48. };
  49. const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
  50. export default withNextIntl(nextConfig);