Lawrence Cooke
Lawrence Cooke

Reputation: 1597

Problems with htaccess rewrite

I am trying to get a couple of directories to always be https and everything else be http

With the exception of images, css files and js files which should be on whatever the page is on.

So I created this htaccess rewrite:

RewriteEngine On
RewriteBase /


RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://server.com/$1 [R=301,L]




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


RewriteRule \.(gif|jpe?g|png|css|js)$ - [NC,L]


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

But when I go to /login I get an error

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

What needs to change for this to work properly?

Upvotes: 1

Views: 55

Answers (2)

anubhava
anubhava

Reputation: 785896

Have your rules in this order:

RewriteEngine On
RewriteBase /

RewriteRule \.(gif|jpe?g|png|css|js)$ - [NC,L]

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{THE_REQUEST} /login/ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NC]

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{THE_REQUEST} !/login/ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L,NC]

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{THE_REQUEST} /login/ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC]

RewriteCond %{HTTP:X-Forwarded-Proto} https
RewriteCond %{THE_REQUEST} !/login/ [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC]

Upvotes: 1

Capsule
Capsule

Reputation: 6159

%{HTTP_HOST} or %{REQUEST_URI} can't be used in the RewriteRule, only in the RewriteCond

You can use %1, %2 etc as a reference to the different matching parts of the condition tho. But the full Request URI can be solved by this in the rewrite rule:

RewriteRule (.*) http://some_host$1

So if the hostname is not dynamic, it's pretty easy to fix.

Upvotes: 0

Related Questions