如何自动将所有非安全 (http) 页面重定向到其对应的 https 页面
http://example.com -> https://example.com
但仅对支持 https 的浏览器执行此操作。这样我的网站仍然可以在旧版浏览器中运行吗?
此重定向代码可以直接添加到 vhost 文件内,也可以添加到 .htaccess 文件内:
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]
在内部,它检查 Upgrade-Insecure-Requests 标头,这是浏览器发送的内容。根据此请求标头,它会重定向页面。