Apache的伪静态规则.htaccess实现301跳转的方法
首先,我们看以下.htaccess文件的伪静态规则,用于实现访问不带www的域名自动跳转到www域名。
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / Order Deny,Allow Deny from 47.114.182.24 RewriteCond %{HTTP_HOST} ^toyean.com [NC] RewriteRule ^(.*)$ https://www.toyean.com/$1 [L,R=301] RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>
其中的“Order Deny,Allow Order from IP地址”这两行规则会禁止指定的IP访问网站,被设置的IP访问网站会显示:
Forbidden
You don't have permission to access / on this server.
若想要禁止多个IP,增加几行“Deny from IP地址”;
不需要禁止某个IP,手动去掉“Order Deny,Allow Order from IP地址”这两行即可。
番外篇总结:
不带www的域名自动跳转到www域名:
RewriteEngine On RewriteCond %{HTTP_HOST} ^toyean.com [NC] RewriteRule ^(.*)$ https://www.toyean.com/$1 [L,R=301]
带www的域名自动跳转到不带www域名:
RewriteEngine On RewriteCond %{HTTP_HOST} ^www.toyean.com [NC] RewriteRule ^(.*)$ https://toyean.com/$1 [L,R=301]
自动跳转到其他域名:
RewriteEngine On RewriteCond %{HTTP_HOST} ^www.toyean.com [NC] RewriteRule ^(.*)$ https://www.wulongmao.com/$1 [L,R=301]