使用 .htaccess
文件来重定向子域是一种常见的方法,通常用于将子域名的请求重定向到另一个网址或域名。本期小编将指导大家如何使用.htaccess重定向子域,方法很简单,一起来看看吧。
下面是如何通过 .htaccess
文件实现子域重定向的步骤:
.htaccess
文件.htaccess
文件,在网站的根目录(通常是 public_html 或网站的根文件夹)中找到它并进行编辑。.htaccess
文件,可以在网站根目录下创建一个新的 .htaccess
文件。假设你要将 subdomain.example.com
重定向到 www.example.com
,可以在 .htaccess
文件中添加如下规则:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteEngine On
:启用 URL 重写引擎。RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
:检查请求的域名是否是 subdomain.example.com
(NC
表示忽略大小写)。RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
:将所有请求重定向到 https://www.example.com
,并将路径保持不变(例如,subdomain.example.com/page
会重定向到 www.example.com/page
)。R=301
表示永久重定向,L
表示这是最后一条规则,处理完后停止继续执行其他规则。subdomain.example.com
重定向到其他域名: apache RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteRule ^(.*)$ https://otherdomain.com/$1 [L,R=301]
subdomain.example.com
、test.example.com
)重定向到主域名: apache RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
这种方式会将所有子域的请求(如 subdomain.example.com
、test.example.com
)都重定向到 www.example.com
。
.htaccess
文件后,保存并上传到你网站的根目录(通常是 public_html
或 www
文件夹)。你可以通过浏览器或工具(例如 httpstatus.io 或 Redirect Checker)测试重定向是否成功。
RewriteEngine
已经开启:如果你已经在 .htaccess
文件中使用了 RewriteEngine On
,无需重复开启。