在使用多个域名时,为避免SEO问题并正确处理内容重复,可以采用301重定向或canonical标签。以下是详细的设置方法和示例:
使用301重定向
301重定向是一种永久性重定向,告诉搜索引擎将一个URL的全部资源重定向到另一个新的URL。
设置方法
- Apache服务器:
在.htaccess文件中添加以下代码:
textRewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com$ [NC]
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
- Nginx服务器:
在server块中添加:
textserver {
server_name olddomain.com www.olddomain.com;
return 301 $scheme://www.newdomain.com$request_uri;
}
- WordPress:
在wp-config.php文件中添加:
phpif ($_SERVER['HTTP_HOST'] != 'www.newdomain.com') {
$redirect = 'http://www.newdomain.com' . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
示例
假设你有三个域名:example.com, example.net和example.org,你希望将所有流量重定向到example.com。
- 对于example.net,设置301重定向: text
RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?example\.net$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
- 对于example.org,同样设置: text
RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?example\.org$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
使用Canonical标签
Canonical标签用于指定首选URL,特别适用于内容相似但URL不同的情况。
设置方法
在HTML的
部分添加:xml<link rel="canonical" href="http://www.example.com/preferred-page" />
示例
假设你有一个产品页面,可通过多个URL访问:
- http://www.example.com/product?id=123
- http://www.example.com/product/123
- http://www.example.com/item/product-name
在这三个页面的
部分都添加:xml<link rel="canonical" href="http://www.example.com/product/123" />
这告诉搜索引擎http://www.example.com/product/123是首选URL。
注意事项
- 确保所有重定向和canonical标签指向正确的URL。
- 避免链式重定向,直接指向最终目标URL。
- 对于大型网站,使用sitemap.xml文件指定规范URL。
- 定期检查重定向是否正常工作,可使用在线工具如Screaming Frog或Google Search Console。
- 如果使用WordPress,可以利用插件如Yoast SEO来管理canonical标签。