【问题标题】:Force non-www/http to www/https only for some specific pages仅针对某些特定页面将非 www/http 强制为 www/https
【发布时间】:2020-09-26 10:18:50
【问题描述】:

我想知道是否可以将某些特定页面从非 www/http 强制转换为 www/https,并保留其他一些非 www/http 的页面。

示例

从非www/http到www/https:

http://example.comhttps://www.example.com

但这些将保持非 www 和 http:

http://example.com/folder1/*

http://example.com/folder2/*

我已尝试在 htaccess 文件中添加此规则条件:

RewriteEngine On     

# Enable HTTPS and WWW for homepage
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{HTTPS} off
RewriteRule ^$ https://example.com/ [R=301,L]

# Disable HTTPS and WWW for all pages
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{HTTPS} on
RewriteRule . http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

然后它应该强制 https 和 www 只是主页并将 /folder1//folder2/ 等其他页面留给 htpp 非 www。

但似乎效果不佳

【问题讨论】:

  • “但似乎效果不佳”究竟是什么意思?它是否有效但未达到预期?它有时会起作用吗?某事有效,其他事无效,哪个?您的错误日志文件中是否有任何条目?宇宙会内爆吗?
  • 第二部分永远不会奏效。它尝试从 https 协议重定向到 http 协议。今天的浏览器都不会出于很好的理由遵循这样的重定向。它们都会显示错误或警告并提示用户做什么。根本没有办法解决这个问题。再说一遍:有很好的理由......
  • 其实这整个问题听起来有点像“xy 问题”。这样您就没有告诉我们您的实际问题,而是询问您如何实施您认为可以解决您的实际问题的一些想法。我建议您改为提出您的实际问题。

标签: .htaccess mod-rewrite http-redirect


【解决方案1】:

试试这个:

RewriteEngine  On
RewriteCond    %{HTTPS} off       ## http requests only
RewriteRule    ^folder1/  - [L]   ## stop for folder1/ 
RewriteRule    ^folder2/  - [L]   ## stop for folder2/
                                  ## then redirect all other requests:
RewriteRule    ^(.*)$     https://www.example.com%{REQUEST_URI} [END,NE,R=permanent] 

同样,您可以正则表达式您的跳过:

RewriteRule    ^folder(\d+)/  - [L]   ## stop redirection for any folder[number]/

或将其设为否定 RewriteCond 保留单个 RewriteRule

RewriteEngine  On
RewriteCond    %{HTTPS} off                        ## http requests only
RewriteCond    %{REQUEST_URI}   !^/folder(\d+)/    ## skip any folder[number]/
RewriteRule    ^(.*)$     https://www.example.com%{REQUEST_URI} [END,NE,R=permanent] 

等等...完整文档:https://httpd.apache.org/docs/2.4/rewrite/flags.html

【讨论】:

    【解决方案2】:

    试试这些:

    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule ^folder1.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule ^folder2.*$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule ^folder1.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.example\.com$
    RewriteRule ^folder2.*$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.example\.com$
    RewriteRule ^folder1.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    等等……

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2011-06-17
      • 2017-12-04
      • 1970-01-01
      • 2014-12-16
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      相关资源
      最近更新 更多