【问题标题】:redirect www to non-www https with apache & .htaccess使用 apache 和 .htaccess 将 www 重定向到非 www https
【发布时间】:2014-10-28 14:40:23
【问题描述】:

我已经看到很多这样的问题被问到,但我还没有找到一个适合我的场景的问题。我几乎尝试了其中的每一个,但无法让它发挥作用。

有人可以解释我如何在没有 www 的情况下让 www.domain.comwww.subdomain.domain.com 重定向到 https 吗?

这是我目前所拥有的:

目前,我有以下 DNS 记录:

A         @                1.2.3.4
A         subdomain        1.2.3.4
CNAME     www              domain.com.
CNAME     www.subdomain    subdomain.domain.com.

我还有一个虚拟主机文件,如下所示(子域的副本也几乎完全相同)

<VirtualHost *:80>
     RewriteEngine on
     ReWriteCond %{SERVER_PORT} !^443$
     RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
</VirtualHost>

<VirtualHost *:443>
    ServerName domain.com
    ServerAlias www.domain.com
    ServerAdmin webmaster@localhost
    DocumentRoot /path/to/public_html

    SSLEngine on
    SSLCertificateFile /path/to/domain.crt
    SSLCertificateKeyFile /path/to/domain.key
    SSLCertificateChainFile /path/to/domain-bundle

    <Directory "/path/to/public_html">
       AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/domain-error.log
    CustomLog ${APACHE_LOG_DIR}/domain-access.log combined
</VirtualHost>

【问题讨论】:

    标签: apache .htaccess redirect web


    【解决方案1】:

    在443虚拟主机中,尝试添加:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [L,R]
    

    【讨论】:

    • 它不会重定向。只是留在https://www.domain.com 并说我的连接不受信任。不过感谢您的建议。
    • @bryan 如果您只有 domain.com 的证书,那么您将总是获得证书异常,因为 SSL 握手发生在请求发送之前,因此您不能在 SSL 握手之前抢先重定向。
    • 你建议我做什么?我不希望www.domain.com 成为一个不存在的域。唯一的办法是为 www 购买另一个证书吗?我的意思是,它至少不应该从您的重写条件重定向吗?似乎很愚蠢,它不会重定向到非 www 因此拥有 SSL 证书。
    • 为 www 和不 www 购买证书
    • 我是否必须同时购买,或者我可以只购买 WWW 并让 domain.com 成功重定向到 www.domain.com 而没有两个证书
    【解决方案2】:

    这就是我学到的。 www.domain.comdomain.com 不同。这也包括子域。理想情况下,您将希望对这两个名称都进行 SSL 认证。但是,如果您像我一样,我并不想花钱。

    如果用户在地址栏中键入以下内容,则以下修复有效:

    http://www.domain.com   => Will be redirected to https://domain.com
    www.domain.com          => Will be redirected to https://domain.com
    https://domain.com      => Will stay as is, secured with no errors.
    https://www.domain.com  => This is the only thing that will give a user a notice.
                               Luckily, I don't see any user typing this into the browser.
    

    我已经从我的 DNS 中删除了以下内容,因为我提出了 www.subdomain.domain.com 不实用的条款,除非我在另一个 CERT 上花费更多的钱,但是如果他们使用 @,我可以接受这个域失败987654325@.

    CNAME     www.subdomain    subdomain.domain.com.
    

    现在这是我的新VirtualHost *:80,我用我的问题中的那个替换了。

    <VirtualHost *:80>
        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*)$ [NC]
        RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
    </VirtualHost>
    

    再次感谢 Jon Lin 的回复和帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2016-12-26
      相关资源
      最近更新 更多