[PHP][HTML][JS] 網頁自動轉址/導向頁面範例 301 & 302

HTML

HTML Meta Refresh 效果同於 JS location.replace(),Browser 不會產生新的 history.state:

<meta http-equiv="refresh" content="0;url=http://code.yidas.com" />

Example HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0;url=http://code.yidas.com" />
    <title>Redirection</title>
</head>
<body></body>
</html>

Front-End Javascript

Replace - 轉導取代 history.state (Moved Permanently)

<script>location.replace("http://code.yidas.com");</script>

Location - 轉導保留 history.state

<script>location.href="http://code.yidas.com";</script>

Back-End

PHP

HTTP Code 302 Found - 暫時轉址

header('Location: https://code.yidas.com');

預設就是302

HTTP Code 301 Moved Permanently - 永久轉址

header("HTTP/1.1 301 Moved Permanently");
header("Location: https://code.yidas.com");

301 轉址只能為Web Server端註記

自定義

// 307 Temporary Redirect
header("Location: https://code.yidas.com", TRUE, 307);

Leave a Reply

Your email address will not be published. Required fields are marked *