簡而言之,我將舊的自定義站點轉換為新的 WordPress 站點,域保持不變,我使用 PHP 將數千篇帶有評論的舊文章插入到 WordPress 資料庫中,保持相同的 id 序列,這意味著如果舊鏈接是:
www.mysite.com/index.php?id=11058
www.mysite.com/index.php?category=12
比新的鏈接是:
www.mysite.com/?p=11058
www.mysite.com/?cat=12
一切都做得很好,唯一的問題是我不想丟失舊的反向鏈接,我想使用PHP進行重定向,例如:
if (isset($_GET['old_id'])) { $id=$_GET['old_id']; $Wordpress_post_id = $id; }
如何在 WordPress 中使用此代碼?這種方法是更好還是通過 .htaccess 重定向?或者有沒有比這兩種更好的方法?
uj5u.com熱心網友回復:
我會這樣做template_redirect:
這個動作鉤子在 WordPress 確定要加載哪個模板頁面之前執行。如果您需要在完全了解被查詢內容的情況下進行重定向,這是一個很好的鉤子。
add_action(
'template_redirect',
static function() {
if(!isset($_GET['old_id'])){
return;
}
// Do custom look up here, possibly get_posts()
// Once you determine where to go, use wp_safe_redirect with the appropriate code (probably 301)
// https://developer.wordpress.org/reference/functions/wp_safe_redirect/
// Also possibly use get_permalink() to find the canonical link for the object
// https://developer.wordpress.org/reference/functions/get_permalink/
}
);
不幸的是,“定制的東西”實際上取決于您存盤東西的方式。是帖子元資料,您是否手動插入帖子ID,是自定義查找表嗎?
如果它是舊 ID 到 PostID 的真正映射,您甚至可以使用帶有簡單規則的Redirection等插件。
uj5u.com熱心網友回復:
由于您提到(并標記),.htaccess您可以在.htaccess檔案頂部(在# BEGIN WordPress評論標記之前)這樣做:
# Redirect "/index.php?id=<number>" to "/?p=<number>"
RewriteCond %{QUERY_STRING} ^id=(\d )
RewriteRule ^index\.php$ /?p=%1 [R=301,L]
# Redirect "/index.php?category=<number>" to "/?cat=<number>"
RewriteCond %{QUERY_STRING} ^category=(\d )
RewriteRule ^index\.php$ /?cat=%1 [R=301,L]
在這兩種情況下,哪里%1是對前面CondPattern中捕獲的組的反向參考。IE。id和categoryURL 引數的值。
使用 302(臨時)重定向進行測驗以避免快取問題。
uj5u.com熱心網友回復:
我最近不得不做同樣的事情。我重新組織了一個站點,并將結構從根目錄(和所有目錄結構)移動到博客檔案夾。我對WordPress的幾種方法進行了試驗,分析了問題的日志等,并實作了以下方法。
首先,我創建了每個頁面、文章等的串列。
然后我在站點根目錄中創建了一個.htaccess檔案。
在下面的示例中,我顯示了一個頁面的重定向,但有兩個條目(尾部斜杠與否)。底部處理檔案和導演等。
我的 .htaccess 大約有 600 行。我沒有注意到重定向有任何性能問題。
注意:我使用 302 進行重定向,如果您的重定向是永久性的,請考慮使用 301。
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteRule ^aboutme$ https://www.example.com/blog/aboutme/ [L,R=302]
RewriteRule ^aboutme/$ https://www.example.com/blog/aboutme/ [L,R=302]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (. )/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378611.html
標籤:php WordPress的 .htaccess 邮政 重定向
