บางครั้งคุณอาจต้องเปลี่ยนเส้นทางトラฟฟิกเว็บไปยังไซต์ใหม่ มีหลายวิธีทำ redirect โดยส่วนใหญ่ผ่านแบ็กเอนด์ แต่บทความนี้ครอบคลุมวิธีทำ client-side redirect ใน HTML
Redirect นี้เกิดในส่วน head ของเอกสาร HTML ในแท็ก meta ไวยากรณ์สำหรับ redirect ให้เราสามารถหน่วงเวลาก่อนเบราว์เซอร์ redirect ไปหน้าใหม่ได้
ไวยากรณ์สำหรับ redirect:
<head> <meta http-equiv="refresh" content="<num seconds>; url=<site to redirect to>"> </head>
แอตทริบิวต์ http-equiv จำลอง HTTP response header ทำให้ refresh เกิดขึ้น แอตทริบิวต์ content ประกอบด้วยจำนวนวินาทีหน่วง refresh (กรณีต้องการส่งข้อความก่อน redirect เช่น bookmark หน้าใหม่เพราะย้ายถาวร, ไซต์ล่มชั่วคราวพาไปเวอร์ชันอื่น)
จำไว้ว่าเวลาวัดเป็นวินาที แต่ในเว็บพัฒนาหลายอย่างวัดเป็นมิลลิวินาที หากใส่ 1,000 คุณหรือลูกค้าจะรอนานมากก่อน redirect จริง
ส่วนที่สองของ content attribute คือ URL ที่จะ redirect ไป ทั้งหมดเกิดใน head ของหน้า HTML
ตัวอย่างในเอกสาร HTML จริง:
html> <head> <head> <meta http-equiv="refresh" content="1; url=https://www.careerkarma.com/blog/html"> </head> <style> body { font-family: 'Roboto'; margin: 20px; } p { margin: 0; padding: 0; } </style> </head> <body> You are being redirect to <a rel="noreferrer noopener" href="https://careerkarma.com/blog/html">https://www.careerkarma.com/blog/html.</a> Please click this link if not redirected in five seconds </body> </html>
หากคุณไม่สามารถใช้แบ็กเอนด์ทำ redirect ได้ ลองพิจารณาตัวเลือกนี้!