Fix “Error too many redirects” in DDEV (Apache / htaccess)

Some web projects have a rewrite rule from HTTP to HTTPs in their .htaccess (for Apache):

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

If you try to open this in DDEV, it will result in “Error too many redirects” because %{HTTPS} will always return “off” in DDEV containers (not sure exactly why, but something technical with reverse proxy behavior).

There is a simple fix which should be applicable on live sites as well. Just add this additional rule for %{HTTP:X-Forwarded-Proto} to your project. It will check if HTTPS is activated via a reverse proxy:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IFModule>

The resulting rewrite rules will only try a redirect if

  • %{HTTPS} is not set to “on”
  • AND
  • %{HTTP:X-Forwarded-Proto} is not “https”

Since DDEV sets X-Forwarded-Proto to “https”, the error should disappear and your live site should work as expected as well.

Gist: https://gist.github.com/mandrasch/228f8fb8f3738fe4c7b8e2295af578aa

Big Thanks to @nurtext: https://gist.github.com/nurtext/b6ac07ac7d8c372bc8eb

See apache-site.conf for more information. If you have a better approach, please let me know in the comments. Thanks!

Leave a Reply