温馨提示×

debian apache如何做重定向

小樊
53
2026-09-24 19:47:29
栏目: 智能运维

在 Debian 上用 Apache 做重定向,通常有以下几种常见方式。下面按使用场景给你说明,并附带示例。


一、开启必要模块(一般默认已开启)

sudo a2enmod rewrite
sudo systemctl restart apache2

二、基于「虚拟主机」做重定向(推荐)

1️⃣ 域名重定向(旧域名 → 新域名)

编辑虚拟主机文件(如 /etc/apache2/sites-available/example.conf):

<VirtualHost *:80>
    ServerName old.example.com
    Redirect permanent / https://new.example.com/
</VirtualHost>

或 301 跳转到带 HTTPS 的:

Redirect 301 / https://new.example.com/

2️⃣ HTTP → HTTPS 重定向

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

三、使用 .htaccess 做重定向(适合目录级)

1️⃣ 启用 .htaccess

在虚拟主机中:

<Directory /var/www/html>
    AllowOverride All
</Directory>

然后重启 Apache。


2️⃣ 常见 .htaccess 重定向示例

✅ 整站重定向到新域名

RewriteEngine On
RewriteCond %{HTTP_HOST} ^old.example.com$ [NC]
RewriteRule ^(.*)$ https://new.example.com/$1 [L,R=301]

✅ 单个页面重定向

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

✅ 去掉 www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]

✅ 加 www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=301]

四、常用命令总结

# 编辑站点配置
sudo nano /etc/apache2/sites-available/xxx.conf

# 启用站点
sudo a2ensite xxx.conf

# 测试配置
apache2ctl configtest

# 重启 Apache
sudo systemctl restart apache2

五、301 vs 302 区别

  • 301:永久重定向(SEO 友好)
  • 302:临时重定向

如果你能告诉我:

  • 是 域名跳转 / 目录跳转 / HTTP→HTTPS
  • 是否使用 虚拟主机还是 .htaccess

我可以给你更精确的配置。

0 踩