Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP to HTTPS .htaccess

Tags:

.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.


1 Answers

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).

like image 125
Jon Lin Avatar answered Nov 30 '25 20:11

Jon Lin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!