【问题标题】:Force HTTPS using .htaccess doesn't always work使用 .htaccess 强制 HTTPS 并不总是有效
【发布时间】:2018-07-17 00:02:58
【问题描述】:

有这个规则

RewriteEngine On
RewriteBase /

# For API
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule (^api\/) api.php [QSA,L]
RewriteRule ^ /index.html
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect 301: from http to https    
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

在这种情况下重定向可以正常工作:

但不是在这种情况下

响应头

我做错了什么?

【问题讨论】:

  • 在禁用缓存的 chrome 开发工具中测试并粘贴有问题的响应标头。
  • @anubhava 我添加了响应头

标签: apache .htaccess https url-rewriting url-redirection


【解决方案1】:

使用不同的规则顺序和DirectoryIndex 指令:

DirectoryIndex index.html
RewriteEngine On
RewriteBase /

# Redirect 301: from http to https and www to non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

RewriteRule ^ - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# For API
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^api/ api.php [NC,L]

确保使用新的浏览器进行测试以避免旧的缓存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2013-05-31
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    相关资源
    最近更新 更多