使用mod_rewrite强制SSL/HTTPS

27 mod-rewrite ssl https redirect

我有一个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
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助!

rap*_*sse 52

我找到了一个适用于代理服务器和未代理服务器的解决方案.

如果您正在使用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
Run Code Online (Sandbox Code Playgroud)

  • 使用Cloudflare灵活SSL时,此答案的确定+1; 所有其他解决方案似乎都会创建重定向循环 (5认同)
  • 将此用于 Heroku。凉爽的! (3认同)

Gum*_*mbo 37

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

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)


小智 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]
Run Code Online (Sandbox Code Playgroud)

这是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]
Run Code Online (Sandbox Code Playgroud)


Hav*_*ard 2


RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^.*$ https://mydomain.com/\0 [L,QSA,R=301]
Run Code Online (Sandbox Code Playgroud)