温馨提示×

centos下apache怎么重定向

小樊
48
2026-10-14 18:18:20
栏目: 智能运维

在 CentOS 下,Apache 的重定向一般通过 mod_alias、mod_rewrite 或 虚拟主机配置 来实现。下面按常见场景说明。


一、准备工作(CentOS)

  1. 安装 Apache(如未安装)
sudo yum install httpd
  1. 启动并设置开机自启
sudo systemctl start httpd
sudo systemctl enable httpd
  1. 确认模块已启用(CentOS 默认启用)
httpd -M | grep rewrite

应看到:

rewrite_module (shared)

如需启用:

sudo vi /etc/httpd/conf.modules.d/00-base.conf

确保有:

LoadModule rewrite_module modules/mod_rewrite.so

二、使用 Redirect(最简单)

1. 整个站点重定向

编辑虚拟主机或主配置:

<VirtualHost *:80>
    ServerName old.example.com
    Redirect 301 / http://new.example.com/
</VirtualHost>

2. 单个页面重定向

Redirect 301 /old.html http://example.com/new.html

301 永久重定向
302 临时重定向


三、使用 .htaccess(推荐用于目录级)

  1. 允许 .htaccess
<Directory "/var/www/html">
    AllowOverride All
</Directory>
  1. 在网站根目录创建 .htaccess
# 开启重写
RewriteEngine On

# 旧页面到新页面
RewriteRule ^old.html$ http://example.com/new.html [R=301,L]
  1. 重启 Apache
sudo systemctl restart httpd

四、使用 RewriteRule(灵活)

1. 域名重定向

<VirtualHost *:80>
    ServerName old.com
    RewriteEngine On
    RewriteRule ^/(.*)$ http://new.com/$1 [R=301,L]
</VirtualHost>

2. HTTP → HTTPS

<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

五、常见配置文件位置(CentOS)

  • 主配置:/etc/httpd/conf/httpd.conf
  • 虚拟主机:/etc/httpd/conf.d/*.conf
  • 网站目录:/var/www/html

修改后务必:

sudo systemctl restart httpd

六、排错

  1. 重定向不生效
  • 检查 AllowOverride
  • 清除浏览器缓存
  • 查看日志
tail -f /var/log/httpd/error_log
  1. 500 错误
  • 通常是 .htaccess 语法错误

如果你能说明 具体重定向需求(如:域名跳转、HTTP转HTTPS、旧路径到新路径),我可以给你一份可直接用的配置。

0 踩