移除URL特定字符串并重定向:WordPress站点迁移跳转需求
Hey there! Let's get that redirect sorted smoothly for your WordPress site that's been running for a year. Since you're moving from example.com/dev to the root example.com and need every /dev-prefixed page to auto-redirect to its root equivalent (like example.com/dev/country/canada → example.com/country/canada), here are three solid methods to make this happen:
This is the fastest way because it works at the server level, before WordPress even loads. Here's what to do:
- Access your site's root directory via FTP, cPanel File Manager, or your hosting dashboard.
- Open the
.htaccessfile (if you don't see it, make sure hidden files are enabled). - Add the following rules BEFORE the
# BEGIN WordPresssection (this ensures the redirect runs first):
# Redirect all /dev paths to root domain equivalents RewriteEngine On RewriteRule ^dev/(.*)$ /$1 [R=301,L]
R=301: Marks this as a permanent redirect, which is great for SEO (it tells search engines to update their indexes to the new URLs).L: Stops processing any further rewrite rules once this one runs.
- Save the file and test a few old
/devURLs to confirm they redirect correctly.
If you'd rather avoid editing server files, a redirect plugin is perfect. The Redirection plugin is the most popular and reliable choice:
- Go to your WordPress dashboard → Plugins → Add New, search for "Redirection", install and activate it.
- Navigate to Tools → Redirection.
- Click "Add New" to create a new redirect rule:
- Source URL: Enter
/dev/(.*) - Target URL: Enter
/$1 - Under "Match", select "Regex" (regular expression) so the
(.*)captures any path after/dev/and maps it to the target. - Set the Redirect Type to "301 - Permanent".
- Source URL: Enter
- Save the rule, and you're done! Test a few old URLs to verify.
If you're comfortable editing theme files (use a child theme to avoid losing changes when your theme updates), add this snippet to your theme's functions.php file:
function redirect_dev_subfolder() { // 检查请求路径是否以/dev/开头 if (strpos($_SERVER['REQUEST_URI'], '/dev/') === 0) { // 替换/dev/为/,获取新的URL路径 $new_path = str_replace('/dev/', '/', $_SERVER['REQUEST_URI']); // 以301状态重定向到新的根路径URL wp_redirect(home_url($new_path), 301); exit; // 确保重定向后停止执行后续代码 } } // 挂钩到template_redirect动作,触发我们的重定向函数 add_action('template_redirect', 'redirect_dev_subfolder');
Save the file, and test your redirects to confirm they work as expected.
小提示:
- 清除缓存: 如果你使用了缓存插件(比如WP Rocket、W3 Total Cache)或者CDN,设置完重定向后一定要清除缓存——旧的缓存内容可能会干扰新规则的生效。
- 301 vs 302: 永久迁移请坚持使用301重定向,这样能保留你的SEO排名。只有临时重定向才用302(你的场景里大概率不需要)。
内容的提问来源于stack exchange,提问作者Fahad Abdullah

