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