Apache在浏览器支持时重定向到HTTPS

tjjdgumg  于 2023-10-23  发布在  Apache
关注(0)|答案(1)|浏览(159)

如何自动重定向所有不安全(http)的网页到他们的https对应http://example.com -> https://example.com,但只对支持https的浏览器这样做。所以我的网站仍然可以在较旧的浏览器中运行?

xuo3flqw

xuo3flqw1#

此重定向代码可以直接添加到vhost文件中,也可以添加到.htaccess文件中:

  1. RewriteEngine on
  2. # rewrite to https.
  3. # -----------------
  4. # %{HTTP:X-Forwarded-Proto} !https: This condition checks if the X-Forwarded-Proto header is not set to https.
  5. # The X-Forwarded-Proto #header is typically set by proxies or load balancers to indicate the original protocol
  6. # used for the request. By checking this header, # you can ensure that the redirect only occurs if the request
  7. # is not already using HTTPS.
  8. RewriteCond %{HTTP:X-Forwarded-Proto} !https
  9. # %{HTTP:Upgrade-Insecure-Requests} ^1$: This condition checks if the Upgrade-Insecure-Requests header is set to 1.
  10. # The Upgrade-Insecure-Requests header is sent by modern browsers that support HTTPS and can automatically upgrade
  11. # an insecure request to a secure one. By checking this header, you can verify if the browser supports HTTPS and
  12. # wants to upgrade the request to HTTPS.
  13. RewriteCond %{HTTP:Upgrade-Insecure-Requests} ^1$
  14. # RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
  15. RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]

在内部,它检查Upgrade-Insecure-Requests头,这是浏览器发送的内容。基于此请求标头,它重定向页面。

展开查看全部

相关问题