为CloudFlare用户强制使用.htaccess进行HTTPS和非WWW

时间:2018-08-21 14:35:23

标签: apache .htaccess ssl mod-rewrite cloudflare

我正在使用CloudFlare,我想通过使用.htaccess强制HTTPS和非WWW

我知道已经有很多在线示例,但是对于CloudFlare用户,正常的重定向可能会导致重定向循环。

最接近的答案是这个:https://stackoverflow.com/a/34065445/1254581

但是它仅强制使用HTTPS,我也需要强制使用非WWW。请帮助编辑此规则:

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]

# Put the rest of your rewrite rules here`enter code here`

1 个答案:

答案 0 :(得分:1)

使用Cloudflare,您可以使用:

RewriteEngine On
# www -> https without www
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R=301]
# http -> https
# # With Cloudflare
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
# # Without Cloudflare
# RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]