LobsterMan
LobsterMan

Reputation: 1208

.htaccess rules - Too many redirects

I'm trying to accomplish 2 things with htaccess file:

  1. Force https on all but 2 directories, only if accessed from prod url (no https on dev)
  2. Redirect any nonexisting url in index.php

this is what I have:

RewriteEngine On
# Redirect all http to https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} myserver\.com$ [NC]
RewriteRule ^(api|images)($|/) - [L]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# The following rewrites all other queries to index.php. The 
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to 
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size 
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

When I add the first bit (the https enforce) I get "too many redirects" error. Any Idea why?

Upvotes: 1

Views: 1215

Answers (2)

anubhava
anubhava

Reputation: 785146

A RewriteCond is only applicable to next RewriteRule. Your redirect rule for http->https is unconditional and will cause a redirect loop.

Have it this way:

RewriteEngine On

# Redirect all http to https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} myserver\.com$ [NC]
RewriteCond %{THE_REQUEST} !\s/+(?:api|images)[/?\s] [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# The following rule tells Apache that if the requested filename
# exists, simply serve it.

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# The following rewrites all other queries to index.php. The 
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to 
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size 
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

RewriteRule ^ %{ENV:BASE}index.php [L]

Upvotes: 1

akond
akond

Reputation: 16035

I believe this part should look more like:

RewriteRule ^(api|images)($|/) - [L]
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} myserver\.com$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Upvotes: 0

Related Questions