【问题标题】:Redirect Main URL to HTTPS, All Subdomains to HTTP but keep existing rules将主 URL 重定向到 HTTPS,将所有子域重定向到 HTTP,但保留现有规则
【发布时间】:2018-02-26 21:37:27
【问题描述】:

目前正在做某事,需要帮助处理我的 htaccess 文件。

我现在已经设置好了,它正在按照我想要的方式工作,它将删除尾部斜杠,并删除 .php,使其看起来像一个目录。它还将 bar.example.com 重定向到文件 example.com/thing?foo=bar

我想使用我购买的 SSL 证书并在任何主域页面上强制使用 HTTPS,但在访问子域时强制使用 HTTP,因为我的证书不是通配符。

感谢您的任何帮助,我目前所拥有的将在下面发布。

RewriteEngine on
Options +FollowSymLinks

RewriteCond %{HTTP_HOST} !^www\.example.com
RewriteCond %{HTTP_HOST} ^(.+).example.com
RewriteRule ^([^/]*)$ http://example.com/thing?foo=%1 [P,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/$1 [R=301,L]
RewriteRule ^([^/.]+)$ $1.php [L]

【问题讨论】:

    标签: php .htaccess


    【解决方案1】:

    将现有条件直接重定向到 https://,然后添加检查 %{HTTPS} 的新规则。请参阅Apache docs 了解更多信息。

    RewriteEngine on
    Options +FollowSymLinks
    
    RewriteCond %{HTTP_HOST} !^www\.example.com
    RewriteCond %{HTTP_HOST} ^(.+).example.com
    # CHANGE: Redirect your subdomains directly to the secure target URL
    RewriteRule ^([^/]*)$ https://example.com/thing?foo=%1 [P,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    # CHANGE: same goes for the folders
    RewriteRule ^([^/]+)/$ https://example.com/$1 [R=301,L]
    RewriteRule ^([^/.]+)$ $1.php [L]
    
    # NEW: Redirect everything else that comes in on `http://www.`
    RewriteCond %{HTTP_HOST} ^www\.example.com
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://www.example.com/$1 [R=301,L]
    

    【讨论】:

    • 所以,这并没有强制 example.com 到 example.com。而且,它将我的 URL 从 bar.examle.com 更改为 example.com/thing?foo=bar 并显示完整的 URL 而不是 bar.example.com
    • http://www.example.comhttps://www.example.com 的重定向应该可以工作。如果您想匹配http://example.com,请省略www\. 或在RegEx ^(www\.)?example\.com 中将其设为可选。但是当您在第一条规则中检查它时,我认为这就是您的设置方式。 “它将我的 URL 从 bar.examle.com 更改为 example.com/thing?foo=bar ”这就是您的第二条规则所做的。这不是预期的行为吗?
    • 不,它应该保留 URL,但代理它曾经和仍在做的页面,但现在它显示了丑陋的 URL。
    • 我使用了您的代码,效果很好,我不得不更改一行,否则它会不断给出 500 内部服务器错误。 RewriteRule ^([^/]*)$ example.com/thing?foo=%1 [P,L] 必须没有 https。
    • @RyanNacker 如果此答案解决了您的问题,请考虑接受并因此将此问题标记为已回答。
    猜你喜欢
    • 2015-03-09
    • 2014-05-28
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2017-04-22
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多