首页 > 解决方案 > 将所有可能的域和子域永久重定向到不带 www 的 https (https://example.com)

问题描述

我有一个访问量很大的网站,因此性能至关重要。我正在使用 apache 和 ubuntu。

我正在尝试将所有可能的域可能性重定向到https://example.com包括所有子域(https://test.example.com)。

这是我目前拥有的:

RewriteEngine On

# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]

# match urls that are non https (without the www)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)(.*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

我觉得上面的代码正在做额外的重新路由/工作。在虚拟主机文件或 .htaccess 中是否有更直接的解决方案(以获得更快的性能)?

谢谢!

标签: apacheperformance.htaccessmod-rewritehttps

解决方案


您可以结合所有三个条件

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

说明:如果not https OR not example.com然后重定向到https://example.com/xxx

回答您关于性能的问题:重写.htaccess可能比在 Apache 配置文件中重写要慢。


推荐阅读