Forcing SSL and WWW using .htaccess

2020-02-07 17:05发布

I would like to know if this code in .htaccess for forcing SSL and WWW in URL is correct, because with another codes I usually get redirect loop, e.g. RewriteCond %{HTTPS} !=on and now it works like a charm (suspiciously). Also, is possible to write it better/simplier?

# Force to SSL
RewriteCond %{HTTP:HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force to WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]  

6条回答
我想做一个坏孩纸
2楼-- · 2020-02-07 17:10

9 Force www: is perfect thank you.

My server is Heart Internet and the force SSL for Heart is:

# All calls go to SSL
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-07 17:25

Use this:

RewriteEngine on

# Force www: from http://stackoverflow.com/a/4958847/1078583
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force SSL: From http://stackoverflow.com/q/24322035/
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,NE]
查看更多
smile是对你的礼貌
4楼-- · 2020-02-07 17:27

I found a mod_rewrite solution that works well for both proxied and unproxied servers.

If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.

RewriteEngine On

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
查看更多
We Are One
5楼-- · 2020-02-07 17:29

That's a bit simpler.

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]
查看更多
可以哭但决不认输i
6楼-- · 2020-02-07 17:29

No need for filling in a domain. This is forcing WWW and HTTPS in any case. This is dealing with subfolder as well.

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
查看更多
Deceive 欺骗
7楼-- · 2020-02-07 17:37

Sorry for bumping this topic but I just wanted to add a simple solution for search engine visitors.

RewriteEngine on
# Force WWW & SSL
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.stackoverflow.com/$1 [L,R=301] 
查看更多
登录 后发表回答