在 Ubuntu + Apache2 下设置 301 永久重定向(跳转),常见有几种方式。下面按最常用 → 进阶给你说明,你可以直接照用。
.htaccess(适合虚拟主机)mod_rewritesudo a2enmod rewrite
sudo systemctl restart apache2
.htaccess编辑你的站点配置(例如):
sudo nano /etc/apache2/sites-available/000-default.conf
在 <Directory /var/www/html> 中加入:
AllowOverride All
示例:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
然后重启 Apache:
sudo systemctl restart apache2
.htaccessnano /var/www/html/.htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^old.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.old.com$
RewriteRule ^(.*)$ https://www.new.com/$1 [L,R=301]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
Redirect 301 /old.html https://www.new.com/new.html
不用 .htaccess,性能更好 ✅
编辑站点配置:
sudo nano /etc/apache2/sites-available/your-site.conf
<VirtualHost *:80>
ServerName old.com
ServerAlias www.old.com
Redirect 301 / https://www.new.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
Redirect 301 / https://www.example.com/
</VirtualHost>
然后:
sudo systemctl restart apache2
<VirtualHost *:443>
ServerName old.com
SSLEngine on
SSLCertificateFile /path/to/cert.crt
SSLCertificateKeyFile /path/to/key.key
Redirect 301 / https://www.new.com/
</VirtualHost>
sudo systemctl restart apache2
apache2ctl -M | grep rewrite
如果你愿意,可以直接把你的 域名 / 需求(如 http→https、旧域名→新域名) 发我,我可以帮你写一份可直接复制的配置。