user5240535
user5240535

Reputation:

HTTP to HTTPS .htaccess

I was unable to comment on a previous post!! I wanted to ask a question as I am new. Is someone able to explain to me what:

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

Actually does in the .htaccess file? and what is the difference between "=" and "!=" I am using Cloudflare and Andrew suggested this config which works but I was looking for a greater understanding of it. To me it says if you get a http request use http. If I change http to https though it says too many redirects. All help appriciated.

Upvotes: 3

Views: 112

Answers (1)

Jon Lin
Jon Lin

Reputation: 143946

The %{HTTP:X-Forwarded-Proto} is a variable that accesses the value of the X-Forwarded-Proto HTTP header, which is used by cloudflare or AWS (or other load balancing services) to indicate the protocol of the original request. This is almost always either "http" or "https".

The mod_rewrite documentation for RewriteCond says:

'=CondPattern' (lexicographically equal)

Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString is lexicographically equal to CondPattern (the two strings are exactly equal, character for character). If CondPattern is "" (two quotation marks) this compares TestString to the empty string.

So in other words, the test string %{HTTP:X-Forwarded-Proto} must equal "http".

Additionally:

You can prefix the pattern string with a '!' character (exclamation mark) to specify a non-matching pattern.

So, != means "not equal".

So the condition tests if the request was originally "http", and if so, the rule redirects the browser to https://%{HTTP_HOST}%{REQUEST_URI} (https).

Upvotes: 3

Related Questions