在 Apache2 中设置重定向,常见方式有以下几种,按使用场景说明:
Redirect(最简单)适用于整站或目录级别的简单重定向。
<VirtualHost *:80>
ServerName example.com
Redirect / https://www.example.com/
</VirtualHost>
.htaccess 中Redirect 301 /old.html https://example.com/new.html
301永久重定向,302临时重定向
mod_rewrite(最灵活,推荐)sudo a2enmod rewrite
sudo systemctl restart apache2
<VirtualHost *:80>
ServerName example.com
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>
RewriteEngine On
RewriteRule ^old-page\.html$ /new-page.html [R=301,L]
RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=123$
RewriteRule ^product\.php$ /new-product? [R=301,L]
.htaccess 文件(适合共享主机)确保 Apache 允许 .htaccess:
<Directory /var/www/html>
AllowOverride All
</Directory>
示例 .htaccess:
RewriteEngine On
RewriteRule ^about$ /about-us [R=301,L]
<VirtualHost *:80>
ServerName old.com
Redirect 301 / https://new.com/
</VirtualHost>
sudo systemctl restart apache2
apache2ctl configtest
如果你有具体场景(如:子目录跳转、带参数、多级域名、Laravel/WordPress),可以告诉我,我可以给你精确配置。