分類
FreeBSD/Linux

Apache使用.htaccess重導新網域

有時因為網域修改, 需要做網域級的重導, 建議使用 301 配合 .htaccess 的設定來進行, 可以使用以下語法:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com$
RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]

其中的 R=301 是使用了 301重導, 而新舊域名可以參考上面語法, 並且使用了 RewriteRule 將任意內容重導至新網域時, 維持相同的網址.

參考資料: https://wpscholar.com/blog/redirect-old-domain-to-new-domain-via-htaccess/

php上實作301 Redirect指示方式

在 php 中若需要重導客戶端, 可以使用 302 重導:

header("Location: http://newlocation");

在不指定 response status 時, 上述內容會使用 302 重導.

若需要使用 301 重導, 可以使用如下程式:

1. 先宣告重導指示, 再進行重導:

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://newlocation");

2. 直接使用 header 中的 response status 參數:

header("Location: http://newlocation", TRUE, 301);

以上兩種方式皆可以重導客戶端至指定目標, 並且以 301 Moved Permanently 方式指示.

繼續閱讀:
https://blog.longwin.com.tw/2015/09/php-301-302-redirect-header-2015/
https://stackoverflow.com/questions/7324645/php-header-redirect-301-what-are-the-implications
https://www.php.net/manual/en/function.header.php

Exit mobile version