【问题标题】:redirect all subdomains from http to https将所有子域从 http 重定向到 https
【发布时间】:2014-05-28 09:01:09
【问题描述】:

我使用以下代码将我的子域的所有 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


    【解决方案1】:

    您可以将其添加到服务器的 .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 将允许虚拟主机充当通配符,然后您可以从主机标头中提取子域并将它们包含在对 https 的重写中

    【讨论】:

    • 这是一种理论上的语法,但没有签名证书就无法工作。
    • 感谢您的回答。我认为这对我有用。但是是否有更简单的语法来执行此操作,例如“重定向 302”
    • @drabo2005 - 什么?这是端口 80 上的虚拟主机 - 即它只提供 HTTP - 此主机不需要证书...
    • @SuperEngineer - 我认为你不能使用RedirectRedirectMatch,因为它们只能在 URL 路径上操作,因此你将无法查询主机头跨度>
    • 您的线路:RewriteCond %{HTTP_HOST} ^(.+)\.subdomain\.com$ 应该是 RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$
    【解决方案2】:

    这是对 .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>
    

    【讨论】:

    • 更简单更完美!
    • 这确实解决了我的问题!见证在这里。
    • 谢谢!谢谢!这只是为新手 Linux 管理员节省了大量时间和搜索!
    【解决方案3】:

    正如RewriteHTTPToHTTPS 的 Apache Wiki 条目所述,

    不推荐使用 mod_rewrite 来执行此操作。见RedirectSSL

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

    <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}),但如果您使用 &lt;Location &gt;,这些变量将被分配。

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

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

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

    【讨论】:

    • 这不起作用。缺少重定向到的 URL,尽管根据您的报价和我的研究,我也认为重写是错误的方法。
    • @PauloNeves 可能有不同的原因、错误的虚拟主机配置或不支持 指令的过时 apache。尝试将日志级别设置为调试以了解更多信息:httpd.apache.org/docs/2.4/mod/core.html#loglevel
    • @PauloNeves 这个解决方案在我手中有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2015-03-09
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多