本文介绍如何在apache服务器上配置301重定向,主要通过.htaccess文件或httpd.conf文件实现。
方法一:使用 .htAccess 文件
此方法适用于大多数情况,无需重启Apache服务器。
-
在需要重定向的目录下创建(或编辑).htaccess文件。例如,将example.com/oldpage.html重定向到example.com/newpage.html,则.htaccess文件应放在与oldpage.html相同的目录。
-
在.htaccess文件中添加以下代码:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^oldpage.html$ /newpage.html [R=301,L]
代码解释:
- RewriteEngine On: 启用URL重写引擎。
- RewriteCond %{REQUEST_FILENAME} !-f: 检查请求的文件是否不存在。
- RewriteCond %{REQUEST_FILENAME} !-d: 检查请求的目录是否不存在。
- RewriteRule ^oldpage.html$ /newpage.html [R=301,L]: 如果以上条件满足,则将oldpage.html永久重定向到newpage.html。R=301指定301重定向,L表示停止后续规则匹配。
方法二:使用 httpd.conf 文件
此方法需要重启Apache服务器才能生效。
-
找到Apache配置文件httpd.conf,位置通常在/etc/apache2/ (linux) 或 C:Program Files (x86)Apache GroupApache2conf (windows)。
-
找到
区块,修改AllowOverride None为AllowOverride All,允许.htaccess文件生效。例如:
<Directory> Options Indexes FollowSymLinks AllowOverride All <!-- 修改此处 --> Require all granted </Directory>
-
保存并关闭httpd.conf文件。
-
重启Apache服务器(Linux: sudo systemctl restart apache2;Windows: 在服务管理器中重启Apache服务)。
-
在目标目录下创建或编辑.htaccess文件,并按照方法一添加重定向规则。
通过以上步骤,即可成功配置Apache服务器的301重定向。 记住,选择哪种方法取决于你的服务器配置和权限。 如果可以,建议优先使用.htaccess方法,因为它更灵活且无需重启服务器。