Force HTTPS and Non-WWW with .htaccess for CloudFlare Users

北城余情 提交于 2019-12-20 06:41:51

问题


I am using CloudFlare and I want to force HTTPS and Non-WWW by using .htaccess

I know there are many examples online already, but for CloudFlare users, normal redirect may cause redirect loops.

The closest answer is this one: https://stackoverflow.com/a/34065445/1254581

But it only force HTTPS and I need to force non-WWW too. Please help to edit this rules:

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:


With Cloudflare, you can use:

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]


来源:https://stackoverflow.com/questions/51951082/force-https-and-non-www-with-htaccess-for-cloudflare-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!