【问题标题】:Redirect to HTTPS with .htaccess with a specific domain使用特定域的 .htaccess 重定向到 HTTPS
【发布时间】:2023-04-05 10:03:01
【问题描述】:
我目前有 2 个域可以访问我服务器上的同一文件夹:metrikstudios.com 和 ziced.com。
我希望通过 http://metrikstudios.com 进入的用户被重定向到 https://metrikstudios.com 和通过http://ziced.com 进入的用户不要被重定向到https://ziced.com。
我目前在我的 .htaccess 中有这个
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
谢谢
【问题讨论】:
标签:
.htaccess
redirect
https
【解决方案1】:
您可以简单地添加另一个 RewriteCond 来检查主机是否为 metrikstudios.com
RewriteCond %{HTTP_HOST} ^metrikstudios\.com [NC]
它应该是这样的:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^metrikstudios\.com [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}
【解决方案2】:
上面接受的解决方案仅将 non-www 域从 http 重定向到 https 。
如果您想将您的域的www 和non-www 版本都重定向到ssl,请将以下RewriteCond 放在您的http 到https 规则的正上方或RewriteCond %{HTTPS} off 行之前:
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
这是将特定域重定向到 https 的完整规则。
RewriteEngine on
# First we will check the host header (url)
#if it's www.example.com or example.com
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
# now we will check the https header
# if https is off (Is non-ssl)
RewriteCond %{HTTPS} off
#redirect the request to https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
【解决方案3】:
有时您可能只想在实时服务器上重定向并保留其本地设置。例如,如果您在本地机器上注册了名为www.mysite.loc 的本地主机,并在该主机上设置了项目的本地实例。
在这种情况下,这也可能对某人有所帮助:
RewriteEngine On
RewriteCond %{HTTPS} =off
RewriteCond %{HTTP_HOST} !.loc$ [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
其中!.loc$ - 如果主机以.loc 结尾,则忽略重定向到https 的规则。
【解决方案4】:
Linux 和 cPanel 基于 Linux 的帐户使用
.htaccess
处理重定向的文件。
注意:如果你需要创建一个 .htaccess 文件,你可以使用你的
控制面板的文件管理器(Web & Classic / cPanel)。
在您的 .htaccess 文件中使用以下代码会自动将访问者重定向到您网站的 HTTPS 版本:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
If you have an existing .htaccess file:
不要重复 RewriteEngine On。
确保以 RewriteCond 和 RewriteRule 开头的行紧跟在已经存在的 RewriteEngine On 之后。
Windows 和 Plesk
基于 Windows 的帐户使用 web.config 文件来处理重定向。
注意:如果您需要创建 web.config 文件,可以使用控制面板的文件管理器(Web & Classic / Plesk)。
在您的 web.config 文件中使用以下代码会自动将访问者重定向到您网站的 HTTPS 版本:
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
如果您有现有的 web.config 文件:
确保您有以下部分(即开始和结束标签):
system.webServer(包含重写)
重写(包含规则)
规则(包含一个或多个规则部分)
插入任何不存在的部分。
在规则部分中插入整个规则部分,包括匹配、条件和操作。
注意:您是在规则(带“s”)部分中插入规则(不带“s”)。