如何将所有 URL 仅定向到 https www 版本

如何将所有 URL 仅定向到 https www 版本

在 Drupal 上的 httaccess 文件中,我希望每个 URL 最终都重定向到 https www site org(请注意“s”和“www”)

我可以完成以下工作:

  1. www.site 自动重定向至 https www.site
  2. http www.site 重定向至 https www.site

我无法得到:

  1. https 网站重定向到 https www.site - 相反,它会转到 https 网站
  2. http 站点自动重定向到 https www.site - 相反,它会转到 https 站点
  3. 网站自动重定向到 https www.site - 相反,它会转到 https 网站

以下是目前的 httaccess 代码:

 # Set "protossl" to "s" if we were accessed via https://.  This is used later
 # if you enable "www." stripping or enforcement, in order to ensure that
 # you don't bounce between http and https.

 RewriteEngine on
  RewriteRule ^ - [E=protossl:s]
  RewriteCond %{HTTPS} off
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

感谢您的帮助

答案1

# RewriteCond %{HTTP_HOST} .
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

在您发布的代码中,最后一部分(注释掉)看起来它应该可以满足您的要求 - 所以您只需取消注释最后 3 行!?

然而,您还应该更改这些指令的顺序,以避免在请求表单的 URL 时出现多次重定向http://example.com

例如:

RewriteEngine on

# Set "protossl" to "s" if we were accessed via https://.  This is used later
# if you enable "www." stripping or enforcement, in order to ensure that
# you don't bounce between http and https.
RewriteRule ^ - [E=protossl:s]

# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/foo will be redirected to http://www.example.com/foo)
# uncomment the following:
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# HTTP to HTTPS redirect (By this stage the HTTP_HOST is already canonicalised)
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Other...
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

与往常一样,在测试之前清除浏览器缓存。

相关内容