[ad_1]
当您将网站移至新域时,您需要将页面重定向到另一个域。 以下是使用 .htaccess 文件轻松将页面重定向到另一个域的方法 Apache 网络服务器。 有多种方法可以将页面重定向到另一个域。 我们将研究它们中的每一个。
如何使用 .htaccess 文件将页面重定向到另一个域
以下是使用 .htaccess 文件将页面重定向到另一个域的步骤。 请确保您已启用 mod_rewrite Apache 网络服务器配置。 只有这样你的 .htaccess 配置才会被应用 Apache 服务器。
如果您使用 mod_rewrite 启用了 htaccess,则可以跳到步骤 4。
1. 启用 mod_rewrite
打开终端并运行以下命令以在 Ubuntu/Debian 系统上启用 mod_rewrite。
$ sudo a2enmod rewrite
如果 mod_rewrite 已启用,您将看到一条警报消息。
重新开始 Apache 网络服务器
$ sudo systemctl restart apache2
奖励阅读:如何禁用 Apache 缓存
2.启用.htaccess Apache 服务器
默认情况下, Apache 不允许使用 .htaccess 文件。 所以打开默认 Apache 服务器配置文件
$ sudo vi /etc/apache2/sites-available/000-default.conf
在 行之前添加以下几行。
<Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory>
重新开始 Apache 网络服务器
$ sudo systemctl restart apache2
奖励阅读:如何在中启用 mod_ssl Apache
3.创建.htaccess文件
打开终端并创建 .htaccess 文件
$ sudo vi /var/www/html/.htaccess
确保在 .htaccess 文件的顶部添加以下行
RewriteEngine on
4. 使用 .htaccess 文件将页面重定向到另一个域
假设您想将页面 /product.html 重定向到另一个域 www.newsite.com。 有多种方法可以使用 .htaccess 文件将页面重定向到另一个域。
使用重定向将页面重定向到另一个域
添加以下重定向指令以将您的页面重定向到另一个域。 重定向语句需要 2 个参数 – 源 URL 路径和目标 URL 路径。 您可以使用绝对 URL 路径或相对 URL 路径
Redirect /product.html https://www.newsite.com/product.html
如果你想永久重定向页面到另一个域,只需在Redirect指令后添加301即可,如图
Redirect 301 /product.html https://www.newsite.com/product.html
如果要将所有页面重定向到新的域根目录,只需将以下行添加到 .htaccess
Redirect 301 / https://www.newsite.com/
Redirect 指令将重定向所有以您指定的 URL 前缀(例如 /product.html)开头的 URL。 重定向还会将带有参数的 URL 重定向到新域。
奖励阅读:如何使用 .htaccess 将 404 重定向到主页
使用 RedirectMatch 将页面重定向到另一个域
您还可以使用 RedirectMatch 指令将您的页面重定向到另一个域。
Redirect 语句将重定向以指定 URL 前缀开头的页面,但 RedirectMatch 将重定向与指定正则表达式匹配的所有页面
RedirectMatch 语句需要 2 个参数——匹配的正则表达式和目标 URL 路径。
RedirectMatch ^/product.html https://www.newsite.com/product.html
如果要永久重定向页面到另一个域,只需在 RedirectMatch 指令后添加 301 即可,如图
RedirectMatch 301 ^/product.html https://www.newsite.com/product.html
RedirectMatch 指令将重定向所有以您指定的正则表达式(例如 /product.html)开头的 URL。 RedirectMatch 还将带参数的 URL 重定向到新域
另请阅读:如何用密码保护目录 Apache
5.重启 Apache 服务器
重新开始 Apache 网络服务器
$ sudo systemctl restart apache2
现在你的 Apache Web 服务器将自动将页面重定向到另一个域。
CodePre 可以在几分钟内轻松可视化数据,并在实时仪表板中进行监控。 今天就试试吧!
[ad_2]