温馨提示×

ubuntu apache2怎样做重定向

小樊
45
2026-09-26 09:19:21
栏目: 智能运维

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


一、使用 .htaccess 做重定向(最简单,适合虚拟主机)

1. 开启 .htaccess 支持

编辑站点配置(如 /etc/apache2/sites-available/000-default.conf):

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

然后启用 rewrite 模块并重启:

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 在网站根目录创建 .htaccess

nano /var/www/html/.htaccess

示例 1:域名重定向(旧 → 新)

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

示例 2:HTTP → HTTPS

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

示例 3:页面重定向

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

二、在 Apache 站点配置中做重定向(推荐生产环境)

编辑站点配置:

sudo nano /etc/apache2/sites-available/000-default.conf

1. 整个站点重定向

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

2. HTTP → HTTPS

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

启用站点并重启:

sudo a2ensite 000-default.conf
sudo systemctl restart apache2

三、使用 mod_rewrite(更灵活)

确保模块已开启:

sudo a2enmod rewrite

示例(在 <VirtualHost> 中):

<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteRule ^/blog/(.*)$ https://example.com/articles/$1 [R=301,L]
</VirtualHost>

四、常见注意点

  • ✅ 301 = 永久重定向(SEO 友好)
  • ✅ 302 = 临时重定向
  • ✅ 修改配置后一定要重启 Apache
  • ✅ 使用 apache2ctl configtest 检查语法

如果你能告诉我:

  • 是 HTTP → HTTPS
  • 还是 旧域名 → 新域名
  • 还是 某个路径跳转

我可以直接给你一份可直接用的配置。

0 踩