Apache 重定向将 https 设置为 http 并匹配和不匹配

Apache Redirect setting https to http and matching & not matching

我对 apache 的重定向设置感到困惑。看起来很简单,但我想不通…

在http访问下

 if carts/ and events/* need to redirect to https

我在 sites-enabled/default-http.conf

中添加此设置
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/carts/ [OR]
RewriteCond %{REQUEST_URI} ^/events/*
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</ifModule>

https访问下

 if not carts/ and events/* need to redirect to http

我在sites-enabled/default-https.conf

中添加这个设置
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !(^/carts/) [OR]
RewriteCond %{REQUEST_URI} !(^/events/*)
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</ifModule>

问题是这样的

http 工作正常,但 https 不工作。
https://test.com/test should redirect to http://test.com/test

首先要避免重启 Apache 启用 .htaccess(如果尚未启用)然后在站点根目录 .htaccess 中使用这些规则:

RewriteEngine On

RewriteCond %{THE_REQUEST} /(carts|events)/ [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]

RewriteCond %{THE_REQUEST} !/(carts|events)/ [NC]
RewriteCond %{HTTPS} on
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]

在新浏览器中进行测试以避免旧浏览器缓存。最好在 chrome 开发工具中进行测试,以查看您获得的重定向。