将部分但不是全部域重定向到 https

发布于 2024-10-13 15:19:57 字数 621 浏览 1 评论 0原文

我试图说服 mod-rewrite 将 http://example.com 重定向到 https://example.com 但不重定向 http:// subdomain.example.com

我已将以下内容添加到站点根目录中的 .htaccess 文件中,

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

并且(正如我所想的那样)重定向所有内容,所以然后我尝试了,

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^http://example(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

但这似乎也重定向了所有内容?

I'm trying to convince mod-rewrite to redirect http://example.com to https://example.com but not redirect http://subdomain.example.com

I've added the following to the .htaccess file in the sites root,

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

and that (as I thought it would) redirects everything, so then I tried

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^http://example(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

but that also appears to redirect everything?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞳孔里扚悲伤 2024-10-20 15:19:57

RewriteRule 仅匹配 URL 中主机和之后的部分端口(在 VirtualHost 上下文中)或相对文件系统路径(在 Directory/htaccess 上下文中);因此尝试在 RewriteRule 中匹配主机名是行不通的。

但是 %{HTTP:Host} 将为您提供 Host HTTP 标头,以便 RewriteCond 可以与之匹配:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:Host} =example.com
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R]

缺点是 mod_rewrite 会注意到您有条件重写,具体取决于HTTP 标头,并将添加 Vary: Host 标头。如果您不想这样做,可以先将其存储到一个变量中,然后对该变量执行 RewriteCond:

RewriteRule . - [E=HTTP_HOST_NO_VARY:%{HTTP:Host}]

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{ENV:HTTP_HOST_NO_VARY} =example.com
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R]

RewriteRule only matches on the part of the URL after the host and port (in VirtualHost context) or on the relative filesystem path (in Directory/htaccess context); so trying to match a hostname in a RewriteRule will not work.

However %{HTTP:Host} will give you the Host HTTP header, so that RewriteCond can match against it:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:Host} =example.com
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R]

The drawback is that mod_rewrite will notice that you rewrite conditionally depending on an HTTP header, and will add a Vary: Host header. If you don't want that, you may store it to a variable first, and do the RewriteCond on that variable:

RewriteRule . - [E=HTTP_HOST_NO_VARY:%{HTTP:Host}]

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{ENV:HTTP_HOST_NO_VARY} =example.com
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文