🥰Sử dụng next.config chuyển localhost:3000 sang http://localhost:3000/en cách hay nhất (ok)
next.config.js
/** @type {import('next').NextConfig} */
module.exports = {
async redirects() {
return [
{
source: '/',
destination: '/en', // hoặc '/vi' tùy ngôn ngữ mặc định
permanent: true, // permanent: false: Dùng redirect tạm thời (status code 307). Nếu bạn muốn redirect vĩnh viễn (301), đặt thành true.
},
];
},
};
Để tự động chuyển hướng từ http://localhost:3000 sang http://localhost:3000/en hoặc http://localhost:3000/vi trong Next.js, bạn có thể sử dụng tính năng redirects() trong file next.config.js.
Dưới đây là cách cấu hình để làm điều đó:
✅ Cách làm với module.exports trong next.config.js
module.exports trong next.config.jsjsCopyEdit/** @type {import('next').NextConfig} */
module.exports = {
async redirects() {
return [
{
source: '/',
destination: '/en', // hoặc '/vi' tùy ngôn ngữ mặc định
permanent: false,
},
];
},
};👉 Giải thích:
source: '/': Trang gốc (http://localhost:3000)destination: '/en': Ngôn ngữ mặc định (có thể thay bằng/vinếu bạn muốn tiếng Việt làm mặc định)permanent: false: Dùng redirect tạm thời (status code 307). Nếu bạn muốn redirect vĩnh viễn (301), đặt thànhtrue.
🔄 Nếu bạn muốn chuyển hướng theo ngôn ngữ trình duyệt?
Bạn sẽ cần xử lý điều này bằng middleware (middleware.ts) trong Next.js 13+ hoặc thủ công trong _middleware.ts nếu dùng Next.js 12.
Bạn muốn mình hướng dẫn thêm phần tự động detect ngôn ngữ trình duyệt không, hay bạn chỉ cần redirect tĩnh / → /en hoặc /vi?
Last updated
Was this helpful?