使用mod_rewrite强制SSL / HTTPS [重复]

问题描述 投票:25回答:4

这个问题在这里已有答案:

我有一个Zend Framework应用程序,我想使用mod_rewrite强制进入HTTPS。当谈到mod_rewrite时,我很迷茫。这是我应用程序根目录中的当前.htaccess文件。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule !\.(html|htm|php|js|ico|gif|jpg|png|css|csv)$ /subdir/index.php

根据我拥有的内容强制应用程序进入HTTPS的最佳方法是什么?我已经尝试了一些我在这里找到的例子,但是当我尝试它时,我不断得到重定向循环或内部服务器错误。

谢谢你的帮助!

mod-rewrite redirect ssl https
4个回答
50
投票

以下解决方案适用于代理服务器和未代理服务器。因此,如果您正在使用CloudFlare,AWS Elastic Load Balancing,Heroku,OpenShift或任何其他Cloud / PaaS解决方案,并且您正在体验具有正常HTTPS重定向的重定向循环,请尝试一下。

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

37
投票

将此规则放在当前规则之前:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

5
投票

我也在寻找这个解决方案。我添加了Gumbo的解决方案,它对我很有用。但我原来的不同。我的网站/应用程序重写通过index.php(对于fany urls和../application)重定向所有内容,除了您专门请求的文件。 (就像公共根目录中的图像或其他静态文件一样)这是我原来的,很久以前我在ZF网站上发现的。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

这是Gumbo在整个网站上强制使用SSL的附加规则。到目前为止对我有用。

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

2
投票

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^.*$ https://mydomain.com/\0 [L,QSA,R=301]
© www.soinside.com 2019 - 2024. All rights reserved.