首页 > 解决方案 > .htaccess 代码将访问从 IP 地址重定向到域名

问题描述

我注意到我可以使用导致重复内容的 IP 地址“134.209.16.153”访问我的网站“cbdshopy.co.uk”。

我想将 IP 访问重定向到域。

这是我当前的 .htaccess,它 100% 强制使用 https 和非 www

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
# END WordPress

我试图将以下行添加到我的 .htaccess 以强制 IP 访问域。

RewriteCond %{HTTP_HOST} ^134.209.16.153

像这样

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{HTTP_HOST} ^134.209.16.153
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
# END WordPress

但似乎没有奏效。

请问有什么想法吗?

标签: .htaccess

解决方案


您的规则不起作用,因为您正在检查两个不同的主机标头www.example134.209.16.153. 您只需要检查 IP 主机。

这是更正后的版本:

#redirect ip to domain
RewriteCond %{HTTP_HOST} ^134.209.16.153
RewriteRule ^(.*)$  https://yoursite.com/$1 [R=301,L]
#www to non-www
RewriteCond  %{HTTP_HOST} ^www\.(.+)$
RewriteRule (.*) https://%1/$1 [L,R=301]
#non ssl to ssl
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

确保在测试这些新重定向之前清除浏览器缓存。


推荐阅读