.htaccess 独立于http/https的域重定向,带mod_重写

.htaccess 独立于http/https的域重定向,带mod_重写,.htaccess,http,redirect,mod-rewrite,https,.htaccess,Http,Redirect,Mod Rewrite,Https,我试图用mod_rewrite重定向我的域,但我遇到了一些问题 我想重定向以下请求: mydomain.tld [redirect to] www.mydomain.tld mydomain.tld/xxx.html [redirect to] www.mydomain.tld/xxx.html mydomain.tld/categorie [redirect to] www.mydomain.tld/categorie 因此,域前面没有www的所有请求都必须重定向到www.mydomain.

我试图用mod_rewrite重定向我的域,但我遇到了一些问题

我想重定向以下请求:

mydomain.tld [redirect to] www.mydomain.tld
mydomain.tld/xxx.html [redirect to] www.mydomain.tld/xxx.html
mydomain.tld/categorie [redirect to] www.mydomain.tld/categorie
因此,域前面没有www的所有请求都必须重定向到www.mydomain.tld/

我的特殊功能必须是-无论请求是http还是https:

https://mydomain.tld [redirect to] https://www.mydomain.tld
https://mydomain.tld/xxx.html [redirect to] https://www.mydomain.tld/xxx.html
https://mydomain.tld/categorie [redirect to] https://www.mydomain.tld/categorie
以下是我已经尝试过的:

RewriteCond %{HTTP_HOST} ^mydomain.tld\.de$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.tld/$1 [R=301,L]
但是现在我不知道如何重定向https请求。 如果你能帮助我,那就太好了。 谢谢

编辑

下面的解决方案对我来说很好,但是是否可以使它更容易,或者合并两个块的前两行

RewriteCond %{HTTP_HOST} ^mydomain\.tld$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ http://www.mydomain.tld/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^mydomain\.tld$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://www.mydomain.tld/$1 [R=301,L]
试试这个:

RewriteCond %{HTTPS} ^on$
RewriteRule (.*) https://www.mydomain.com/$1 [R,L]

在阅读mod_rewrite文档之后,人们会尝试使用%{REQUEST_SCHEME},但这是不可靠的

但我们可以这样定义一个等价物:

# Prepare our REQUEST_SCHEME workaround, use with %{ENV:REQUEST_SCHEME}
RewriteCond %{HTTPS} off
RewriteRule .* - [E=REQUEST_SCHEME:http]
RewriteCond %{HTTPS} on
RewriteRule .* - [E=REQUEST_SCHEME:https]

# Redirect mydomain.tld to www.mydomain.tld preserving http[s] scheme
RewriteCond %{HTTP_HOST} ^mydomain\.tld$ [NC]
RewriteRule ^(.*)$ %{ENV:REQUEST_SCHEME}://www.mydomain.tld/$1 [R=301,L]

增强aexl对CloudFlare用户的建议:

RewriteEngine on

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule .* - [E=REQUEST_SCHEME:http]

RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"https"'
RewriteRule .* - [E=REQUEST_SCHEME:https]
好吗


对不起,这不是我想要的:/
RewriteCond %{ENV:HTTPS} on
RewriteRule .* - [E=SSL:s]
RewriteCond %{HTTP_HOST} !^www\.(.*) [NC]
RewriteRule ^(.*)$ http%{ENV:SSL}://www.%{HTTP_HOST}/$1 [R=301,L]