温馨提示×

ubuntu apache2怎样设置重定向

小樊
36
2026-09-17 08:05:50
栏目: 智能运维

在 Ubuntu 上使用 Apache2 设置重定向,常见有几种方式,下面按使用场景给你说明。


一、开启必要模块

大多数重定向需要 rewrite 模块:

sudo a2enmod rewrite
sudo systemctl restart apache2

二、在虚拟主机中配置重定向(推荐)

1️⃣ 域名重定向(如 http → https)

编辑站点配置:

sudo nano /etc/apache2/sites-available/example.conf

示例(HTTP 跳 HTTPS):

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

启用站点并重启:

sudo a2ensite example.conf
sudo systemctl reload apache2

2️⃣ 使用 Rewrite 规则(更灵活)

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

三、在 .htaccess 中设置重定向

适合不能改虚拟主机的情况。

1️⃣ 允许 .htaccess

<Directory /var/www/html>
    AllowOverride All
</Directory>
sudo systemctl reload apache2

2️⃣ 创建 .htaccess

nano /var/www/html/.htaccess

示例:

RewriteEngine On
RewriteRule ^old.html$ new.html [R=301,L]

或全站 HTTPS:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

四、常见重定向示例

✅ 带 www 跳转不带 www

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

✅ 目录重定向

Redirect 301 /old/ /new/

五、检查配置是否正确

sudo apache2ctl configtest

如果你能告诉我:

  • HTTP → HTTPS
  • 还是 域名变更
  • 还是 某个页面跳转

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

0