在 Ubuntu 上使用 Apache2 设置重定向,常见有几种方式,下面按使用场景给你说明。
大多数重定向需要 rewrite 模块:
sudo a2enmod rewrite
sudo systemctl restart apache2
编辑站点配置:
sudo nano /etc/apache2/sites-available/example.conf
示例(HTTP 跳 HTTPS):
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
启用站点并重启:
sudo a2ensite example.conf
sudo systemctl reload apache2
<VirtualHost *:80>
ServerName example.com
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>
适合不能改虚拟主机的情况。
<Directory /var/www/html>
AllowOverride All
</Directory>
sudo systemctl reload apache2
nano /var/www/html/.htaccess
示例:
RewriteEngine On
RewriteRule ^old.html$ new.html [R=301,L]
或全站 HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
Redirect 301 /old/ /new/
sudo apache2ctl configtest
如果你能告诉我:
我可以给你更精确的配置。