如何配置规范主机名并使用apache强制https?

时间:2014-06-27 20:36:16

标签: apache https rewrite

我想始终使用https并拥有一个规范域。问题是当我与辅助域建立https连接时,由于证书是针对主域的,所以一切都崩溃了。有没有办法解决这个问题,还是我必须购买我所有域名的证书,而不仅仅是规范域名?

我的" /etc/apache2/apache2.conf"

的相关部分
# Canonical hostname and always use https
<IfModule mod_rewrite.c>
  RewriteEngine On

  # force https on primary host (works fine)
  # http://primary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^primary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

  # force https and redirect to primary host (works fine)
  # http://secondary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^secondary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

  # FAIL: Certificate doesn't match and "Bad Request (400)" if accepted!
  # https://secondary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} on
  RewriteCond %{HTTP_HOST} ^secondary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

</IfModule>

1 个答案:

答案 0 :(得分:0)

您是否按照此处所述尝试了以下操作? https://httpd.apache.org/docs/2.4/rewrite/remapping.html

  

此规则的目标是强制使用特定主机名,而不是可能用于访问同一站点的其他主机名。例如,如果您希望强制使用www.example.com而不是example.com,则可以使用以下配方的变体。

     

解决方案:   解决这个问题的最佳方法根本不涉及mod_rewrite,而是使用放置在虚拟主机中的Redirect指令作为非规范主机名。

<VirtualHost *:80>
  ServerName undesired.example.com
  ServerAlias example.com notthis.example.com

   Redirect "/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
  ServerName www.example.com
</VirtualHost>

或简称

<If "%{HTTP_HOST} != 'www.example.com'">
    Redirect "/" "http://www.example.com/"
</If>