我有一个在heroku上运行的spa,我想让它在强制https上运行。我正在使用 PHP 堆栈进行一些基本身份验证,没有什么特别的,只有一个 index.php。认为这应该很容易,但我有一个奇怪的重定向: 例如,当我访问/appStart 时,我会在日志中看到以下内容:
10.8.149.25 - - [13/Feb/2021:19:23:57 +0000] "GET /appStart HTTP/1.1" 301 248 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36
这是我的.htaccess:
RewriteEngine On
#Force SSL
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_URI} !\.(png|css|js|json|txt|ico)$
RewriteCond %{REQUEST_URI} !_nuxt
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
我在 .htaccess 中将 https 重写切换为 302,以确保重定向不是来 self 的规则,所以... 这个301是哪里来的???
最佳答案
如果 appStart
是一个物理目录,并且您请求 /appStart
(无尾部斜杠),则 mod_dir (Apache) 将通过 301 重定向“修复”该 URL附加尾部斜杠。 IE。 /appStart/
.
如果 appStart
是物理目录,您应该请求 /appStart/
(带有尾部斜杠)。
UPDATE: Just to be sure:
DirectorySlash Off
will solve my issue, right?
(我假设您的 .htaccess
文件位于 /appStart/.htaccess
?)
实际上比这更复杂一点。如果目录上没有尾部斜杠,则 .htaccess
中的 mod_rewrite 指令将不会被处理,并且 front-controller (内部重写为 index.php
) 将失败。其他问题,例如 DirectoryIndex
(mod_dir) 也会失败 - 尽管您似乎并不依赖于此(您正在使用 mod_rewrite 代替)。
最终结果是,您可能会收到 403 Forbidden 响应(除非您启用了 mod_autoindex - 在这种情况下,您将获得自动生成的目录列表,尽管有 DirectoryIndex
文档存在!请参阅 Apache 文档中的 security warning for the DirectorySlash directive。)
简而言之,Apache 需要尾部斜杠。
如果您使用 DirectorySlash Off
禁用自动附加尾部斜杠,那么您需要自己手动附加此尾部斜杠以避免这些问题。您需要在父/根 .htaccess
文件中执行此操作,而不是 /appStart/.htaccess
。
例如...将现有的 /appStart/.htaccess
文件移动到根 /.htaccess
文件,包括 DirectorySlash Off
指令并将最后一个 RewriteRule
指令更改为:
RewriteRule ^appStart appStart/index.php [L]
但是,这不一定能完全解决问题(取决于应用程序的结构),因为应用程序中的任何相对 URL 路径(静态资源等)现在都相对于文档根目录,而不是相对于文档根目录。 /appStart/
子目录,就像以前一样。这是一个客户端 URL 问题,只能通过“修复”客户端 URL 来解决。
关于.htaccess - 为什么heroku将 "folder-like"请求通过301重定向到http?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66189092/