温馨提示×

ubuntu apache2怎么重定向

小樊
46
2026-09-14 07:53:13
栏目: 智能运维

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


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

1. 开启 .htaccess 支持

编辑站点配置:

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

<VirtualHost *:80> 里加上:

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

启用 rewrite 模块:

sudo a2enmod rewrite
sudo systemctl restart apache2

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

nano /var/www/html/.htaccess

示例 1:整个网站重定向到 HTTPS

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

示例 2:旧页面重定向到新页面

Redirect 301 /old.html /new.html

示例 3:域名重定向

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

二、在 Apache 配置文件中重定向(推荐生产环境)

编辑站点配置:

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

1. HTTP → HTTPS

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

2. 域名跳转

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

保存后:

sudo systemctl restart apache2

三、使用 mod_rewrite 做高级重定向

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

四、常见命令总结

# 启用模块
sudo a2enmod rewrite

# 重启 Apache
sudo systemctl restart apache2

# 检查配置
sudo apache2ctl configtest

五、301 和 302 区别

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

如果你能告诉我:

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

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

0