更改为 https 并重定向到 .htaccess 中的子文件夹规则



我在这里尝试做两件事:

  1. 重定向至子文件夹

    重定向 http://www.something.com/some/page.html或https://www.something.com/some/page.html自https://www.something.com/subfolder/some/page.html

  2. 将 HTTP 重定向到 HTTPS

    重定向http://www.something.com/subfolder/some/page.html自https://www.something.com/subfolder/some/page.html

我想在同一个 .htaccess 文件中同时执行这两个操作

我已经能够通过以下代码重定向到子文件夹:

Options +FollowSymLinks -MultiViews
RewriteEngine on 
RewriteBase / 
RewriteCond %{HTTP_HOST} something.com [NC] 
RewriteRule ^(.*)$ https://www.something.com/subfolder/$1 [R=301,NC]

然后我正在尝试同时执行这两个操作;即http到https(仅在http请求出现时)并通过以下代码重定向到子文件夹:

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
RewriteCond %{HTTP_HOST} something.com [NC] 
RewriteRule ^(.*)$ https://www.something.com/subfolder/$1 [R=301,NC]

但它不起作用。我在这里做错了什么?

编辑

使用@starkeen的解决方案时;即

Options +FollowSymLinks -MultiViews
RewriteEngine on 
RewriteBase / 
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]
RewriteCond %{REQUEST_URI} !^/subfolder
RewriteRule ^(.*)$ https://www.example.com/subfolder/$1 [R=301,NC,L]

我期待以下结果:

https://www.example.com/subfolder/brands/omega.html

当我给出以下任何一项时:

http://example.com/brands/omega.html OK
https://example.com/brands/omega.html OK
http://www.example.com/brands/omega.html OK
https://www.example.com/brands/omega.html OK
http://example.com/subfolder/brands/omega.html WRONG
http://www.example.com/subfolder/brands/omega.html WRONG

但最后两个重定向到

https://www.example.com/subfolder/

下面是在单个规则中执行这两个任务的规则:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{REQUEST_URI} !^/subfolder [NC]
RewriteRule ^(?:subfolder)?(/.*)?$ https://www.example.com/subfolder$1 [NE,L,R=302,NC]

请确保在测试此规则之前清除浏览器缓存。

尝试:

Options +FollowSymLinks -MultiViews
RewriteEngine on 
RewriteBase / 
#--Http ==>https--#
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]
#--exclude the destination to avoid redirect loop--#
RewriteCond %{REQUEST_URI} !^/subfolder
#--redirect /foo to /subfolder/foo--#
RewriteRule ^(.*)$ https://www.something.com/subfolder/$1 [R=301,NC,L]

在测试此重定向之前清除浏览器的缓存。

最新更新