【问题标题】:avoid many redirections when forcing https and www in front of the url在 URL 前面强制使用 https 和 www 时避免多次重定向
【发布时间】:2016-10-20 11:13:57
【问题描述】:

我有一个网站,我正在部署到启用了 https 的服务器。所以我的客户的要求如下:

  1. 强制 https。
  2. 在 url 中保留 www,以便将 url 设为 https://www.example.com,而不是 https://exambple.com,因此 3ws 也是强制的。

我在 .htaccess 文件中使用了这条规则以获得想要的效果:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/es/$1/ [R=301,L]

但是当使用PageSpeed Insights 测试页面速度时,我得到的服务器响应时间很差,只有 1 秒。并且使用 Chrome 开发者工具进行调试,我发现上次重定向后网站的响应时间约为 300 毫秒,因此重定向正在增加响应时间。

那么,我的问题是,如何在最小化重定向的同时强制将 https 和 www 放在 url 前面?

【问题讨论】:

    标签: php apache .htaccess redirect nginx


    【解决方案1】:

    尝试这样做:

    强制 SSL:

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    

    强制万维网:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    

    【讨论】:

      【解决方案2】:

      您可以使用以下规则,将 www 和 https 附加到您的 URL。

      RewriteEngine On
      
      # Ensure www.
      RewriteCond %{HTTP_HOST} !^www\. [NC]
      RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
      
      
      # Ensure https
      RewriteCond %{HTTPS} off
      RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-13
        • 2020-10-15
        • 2018-12-29
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 2017-09-30
        • 1970-01-01
        相关资源
        最近更新 更多