1

How to I automatically redirect all non secure (http) pages to their https counterpart http://example.com -> https://example.com But only do this for browsers which support https. So that my website still works in older browsers?

nathnolt
  • 435
  • 6
  • 8

1 Answers1

0

This redirect code can either be added directly inside of the vhost file, or inside of a .htaccess file:

RewriteEngine on

# rewrite to https.
# -----------------
# %{HTTP:X-Forwarded-Proto} !https: This condition checks if the X-Forwarded-Proto header is not set to https. 
# The X-Forwarded-Proto #header is typically set by proxies or load balancers to indicate the original protocol 
# used for the request. By checking this header, # you can ensure that the redirect only occurs if the request 
# is not already using HTTPS.
RewriteCond %{HTTP:X-Forwarded-Proto} !https

# %{HTTP:Upgrade-Insecure-Requests} ^1$: This condition checks if the Upgrade-Insecure-Requests header is set to 1. 
# The Upgrade-Insecure-Requests header is sent by modern browsers that support HTTPS and can automatically upgrade 
# an insecure request to a secure one. By checking this header, you can verify if the browser supports HTTPS and 
# wants to upgrade the request to HTTPS.
RewriteCond %{HTTP:Upgrade-Insecure-Requests} ^1$

# RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]

Internally, it checks for the Upgrade-Insecure-Requests header, which is something that the browser sends. Based on this request header, it redirects the page.

nathnolt
  • 435
  • 6
  • 8