温馨提示×

ubuntu apache怎样配置重定向

小樊
49
2026-09-29 08:23:35
栏目: 智能运维

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


一、开启必要的 Apache 模块

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

sudo a2enmod rewrite
sudo systemctl restart apache2

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

编辑站点配置,例如:

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

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

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

2️⃣ HTTP → HTTPS 重定向

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

3️⃣ 带 SSL 的虚拟主机示例

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html
    SSLEngine on
    SSLCertificateFile /path/to/cert.pem
    SSLCertificateKeyFile /path/to/privkey.pem
</VirtualHost>

保存后:

sudo apache2ctl configtest
sudo systemctl restart apache2

三、使用 .htaccess 做重定向(灵活但稍慢)

1️⃣ 开启 .htaccess 支持

在虚拟主机中:

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

重启 Apache。

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

HTTP → HTTPS

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

旧页面重定向

Redirect 301 /old.html /new.html

整站重定向

Redirect 301 / http://newdomain.com/

去掉 www

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

四、常用命令总结

sudo a2enmod rewrite
sudo a2ensite your-site.conf
sudo apache2ctl configtest
sudo systemctl restart apache2

五、排查问题建议

  • 清空浏览器缓存(301 会被强缓存)
  • 查看错误日志:
    sudo tail -f /var/log/apache2/error.log
    
  • 使用 curl -I http://域名 检查响应码

如果你有具体重定向需求(例如:子目录、带参数 URL、Laravel、WordPress),可以告诉我,我可以直接给你配置。

0 踩