首页 > 解决方案 > 非 https 主站点重定向到带有目录的 https

问题描述

我正在使用这段代码将我的 .htaccess 文件中的所有 http 重定向到 https。

RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

效果很好。但我唯一的问题是如果我访问 root 非 http

http://example.com redirects to https://www.example.com/dev/

/dev 是主站点所在的目录。

我的cpanel目录是这样的

public_html/dev <---- https://www.example.com

我该如何解决这个问题。它应该重定向到没有 dev 目录的 https 版本。希望有人可以阐明这一点。谢谢。

编辑: 为了更清楚,这里是目录结构 在此处输入图像描述

public_html 中 .htaccess 的内容是

public_html/.htaccess

rewritecond %{HTTP_HOST} ^example.com$ [NC,OR]
rewritecond %{HTTP_HOST} ^www.example.com$
rewritecond %{REQUEST_URI} !dev/
rewriterule (.*) /dev/$1 [L]

RewriteCond %{HTTP_HOST} ^oldurl\.com$ [OR] // if old url redirect to example.com
RewriteCond %{HTTP_HOST} ^www\.oldurl\.com$ // if old url redirect to example.com
RewriteRule ^/?$ "https\:\/\/www\.example\.com" [R=301,L]

这是 public_html/dev 中 .htaccess 文件的内容

public_html/dev/.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off 
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

标签: regexapache.htaccessmod-rewriteurl-rewriting

解决方案


就这样吧。

public_html/.htaccess

RewriteCond %{HTTP_HOST} ^(?:www\.)?oldurl\.com$ [NC]
RewriteRule ^/?$ https://www\.example\.com [R=301,L]

# enforce HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# First add a trailing slash if dev/$1 is a directory
RewriteCond %{DOCUMENT_ROOT}/dev/$1 -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=301,NE]

# forward everything to /dev directory
RewriteCond %{REQUEST_URI} !^/dev/ [NC]
RewriteRule .* dev/$0 [L]

public_html/dev/.htaccess:

RewriteEngine On
RewriteBase /dev/

RewriteRule ^index\.php$ - [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

确保在测试此更改之前完全清除浏览器缓存。


推荐阅读