在 Ubuntu 上通过 Apache 配置重定向,常见有几种方式,下面按使用场景给你说明。
大多数重定向都需要 rewrite 模块:
sudo a2enmod rewrite
sudo systemctl restart apache2
编辑站点配置,例如:
sudo nano /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerName old.example.com
Redirect 301 / http://new.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
Redirect 301 / https://example.com/
</VirtualHost>
<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
在虚拟主机中:
<Directory /var/www/html>
AllowOverride All
</Directory>
重启 Apache。
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
sudo tail -f /var/log/apache2/error.log
curl -I http://域名 检查响应码如果你有具体重定向需求(例如:子目录、带参数 URL、Laravel、WordPress),可以告诉我,我可以直接给你配置。