.htaccess : http to https redirection does not work

ぃ、小莉子 提交于 2019-12-13 01:52:52

问题


I have a problem with my .htaccess and https redirection.

First of all, I have consulted these links to find a solution but none could help me.

List of links :

  • .htaccess redirect http to https
  • ModRewrite with HTTPS
  • https://www.ndchost.com/wiki/apache/redirect-http-to-https
  • htaccess redirect to https://www
  • https://serverfault.com/questions/116206/how-do-i-use-htaccess-to-always-redirect-from-http-to-https

When I load the page with http, the .htaccess redirect me to https but when I load the page with https, I have an infinite loop.

Here is my .htaccess code :

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

RewriteCond %{HTTP_HOST} ^(api|www|dev|stefano|sav)\.
RewriteCond %{REQUEST_URI} !^/(api|www|dev|stefano|sav)/
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*)$ %1/$1 [L]

Is anybody can help me create a redirect condition (http to https) ?


回答1:


You are leaving off the Rewrite Flags You need to tell it force the redirection with R flag and optional provide status code which is recommended 301, 302 etc.

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

By the way, every example you linked to shows the answer using the R flag, not sure why you didn't use exact examples :)

Solution if behind devices like load balancer.

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]



回答2:


I have been fighting with this same problem for hours. It seems that I needed the solution for systems behind a load balancer. Perhaps this is because I am using Cloudflare with my site.

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

After adding the above lines to my .htaccess file, I deleted the cache on Cloudflare and the site loads as it should.



来源:https://stackoverflow.com/questions/34673170/htaccess-http-to-https-redirection-does-not-work

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