在 Ubuntu 上使用 Apache2 做重定向,常见有几种方式,下面按使用场景给你说明。
.htaccess 做重定向(最简单,适合虚拟主机).htaccess 支持编辑站点配置(如 /etc/apache2/sites-available/000-default.conf):
<Directory /var/www/html>
AllowOverride All
</Directory>
然后启用 rewrite 模块并重启:
sudo a2enmod rewrite
sudo systemctl restart apache2
.htaccessnano /var/www/html/.htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^old.com$ [NC]
RewriteRule ^(.*)$ https://new.com/$1 [L,R=301]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Redirect 301 /old.html https://example.com/new.html
编辑站点配置:
sudo nano /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerName old.com
Redirect 301 / https://new.com/
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
Redirect 301 / https://example.com/
</VirtualHost>
启用站点并重启:
sudo a2ensite 000-default.conf
sudo systemctl restart apache2
mod_rewrite(更灵活)确保模块已开启:
sudo a2enmod rewrite
示例(在 <VirtualHost> 中):
<VirtualHost *:80>
ServerName example.com
RewriteEngine On
RewriteRule ^/blog/(.*)$ https://example.com/articles/$1 [R=301,L]
</VirtualHost>
apache2ctl configtest 检查语法如果你能告诉我:
我可以直接给你一份可直接用的配置。