htaccess:强制https和www如果不在localhost上

时间:2022-05-26 11:18:09

I work on my localhost so I need this exception in my mod_rewrite rule. Currently, I am able to force the "www" when not on localhost using the following:

我在我的localhost上工作,所以我在mod_rewrite规则中需要这个例外。目前,我可以在不使用localhost时使用以下方法强制使用“www”:

# Force www, if not in localhost
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Now, I want to also force https (my entire site will be under https). How do I add this to my htaccess?

现在,我还要强制https(我的整个网站将在https下)。如何将此添加到我的htaccess?

I tried making my htaccess like this, but this is forcing https on my localhost also:

我尝试像这样制作我的htaccess,但这也强制我的localhost上的https:

# Force https, if not in localhost
RewriteCond %{HTTP_HOST} !=localhost    
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force www, if not in localhost
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

UPDATE 1: I think I need to remove the first [R=301,L].

更新1:我想我需要删除第一个[R = 301,L]。

UPDATE 2: If I have a URL like this: https://scripts.domain.com, I do not want it to become: https://www.scripts.domain.com.

更新2:如果我有这样的URL:https://scripts.domain.com,我不希望它成为:https://www.scripts.domain.com。

1 个解决方案

#1


5  

Add this line above your last rule:

在最后一条规则上方添加此行:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]{3}$

#1


5  

Add this line above your last rule:

在最后一条规则上方添加此行:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]{3}$