网站301重定向设置方法
301重定向是永久性重定向,用于将旧URL跳转到新URL。
301重定向的用途:
- www与非www统一
- 旧域名跳转新域名
- 更改URL结构后跳转
- HTTP跳转到HTTPS
Apache .htaccess配置:
非www跳转到www:
- RewriteEngine On
- RewriteCond %{HTTP_HOST} ^example.com [NC]
- RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
www跳转到非www:
- RewriteEngine On
- RewriteCond %{HTTP_HOST} ^www.example.com [NC]
- RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
HTTP跳转HTTPS:
- RewriteEngine On
- RewriteCond %{HTTPS} off
- RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
旧域名跳转新域名:
- RewriteEngine On
- RewriteCond %{HTTP_HOST} ^old-domain.com [NC]
- RewriteRule ^(.*)$ http://new-domain.com/$1 [L,R=301]
PHP代码实现:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.newurl.com/");
exit();
?>
注意事项:
- 301是永久重定向,搜索引擎会更新索引
- 302是临时重定向,不传递权重
- 避免重定向循环
- 使用工具检查重定向是否生效