将所有子域名从http重定向到https

问题描述 投票:14回答:2

我使用以下代码将我的子域的所有http请求重定向到https。

<VirtualHost *:80>
  ServerName subdomain.example.com
  Redirect 302 / https://subdomain.example.com
</VirtualHost>

现在我的问题是如何为所有子域做到这一点。

例如,http:subdomain1.example.com应转到https:subdomain1.example.com,http:subdomain2.example.com应转到https:subdomain2.example.com

如何为所有子域执行此操作,而无需为所有子域创建一个虚拟主机

更新

我发现RedirectMatch采用正则表达式。有谁知道如何使用正则表达式?

apache redirect subdomain wildcard-subdomain
2个回答
20
投票

您可以将其添加到服务器的.conf文件中:

<VirtualHost *:80>
  ServerName subdomain.example.com
  ServerAlias *.example.com

  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$
  RewriteRule ^(.*)$ https://%1.example.com$1 [R=302,L]
</VirtualHost>

ServerAlias将允许vhost充当通配符,然后您可以从主机头中提取子域并将其包含在重写为https中


3
投票

这是对.conf文件的简单通用修改:

<VirtualHost *:80>
    #...whatever you already have set up...

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

</VirtualHost>

0
投票

作为RewriteHTTPToHTTPS州的Apache Wiki条目,

使用mod_rewrite执行此操作不是推荐的行为。见RedirectSSL

强制HTTP到HTTPS重定向的vhost配置 - 也适用于子域 - 是这样的:

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

    <Location "/">
        Redirect permanent "https://%{HTTP_HOST}%{REQUEST_URI}"
    </Location>
</VirtualHost>

<VirtualHost *:443>
    [...your vHost configuration...]
    SSLEngine On
    SSLCertificateFile /path/to/your/cert.pem
    SSLCertificateKeyFile /path/to/your/privkey.pem
</VirtualHost>

说明:Redirect和RedirectMatch通常没有Mod_Rewrite中的变量(如{HTTP_HOST}),但如果使用<Location >,则会分配这些变量。

Redirect permanent(替代方案:Redirect 301)将使用http 301代码重定向,因为

301重定向被视为用于将用户从HTTP升级到HTTPS的best practice

注意:此配置基于子域的Wildcard Certificates

© www.soinside.com 2019 - 2024. All rights reserved.