让我们有一个包含代码的index.php:
session_start();
$_SESSION['foo'][] = 'bar';
print_r($_SESSION['foo']);
通常它会为 1 次刷新添加一个选项卡索引,如下所示:
起始页:数组 ( [0] => bar )
第一次刷新:Array ( [0] => bar [1] => bar )
第二个:数组 ( [0] => bar [1] => bar [2] => bar )
(...)
但是当我使用带有 base: RewriteBase/
的 htaccess 重写时,看起来脚本执行了两次以进行 1 次刷新。
输出如下:
起始页:数组 ( [0] => bar )
第一次刷新:Array ( [0] => bar [1] => bar [2] => bar )
第二个:数组 ( [0] => bar [1] => bar [2] => bar [3] => bar [4] => bar )
(...)
为什么会发生这种情况以及如何防止这种行为?
完成.htaccess
Options -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
//empty row
更新:
我刚刚检查了当我在本地主机/文件夹上运行脚本时它可以正常工作。 我上面描述的情况发生在虚拟主机上..
在 Firefox 上它输出(虚拟主机):
起始页:数组 ( [0] => bar )
第一次刷新:Array ( [0] => bar [1] => bar [2] => bar [3] => bar )
之后每次刷新=表中1个新索引..令人困惑
最佳答案
第一句话
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
这部分代码将永远执行,因为上一个 block 将所有内容重写到索引文件(现有文件/文件夹/符号链接(symbolic link)除外)。您必须将其放在第一个 block 之前。
第二条评论
由于您对索引进行了两次调用,因此我怀疑存在 favicon
问题。基本上,当您尝试访问某个页面时,许多浏览器都会向 http://website.com/favicon.ico
发出并行 http 请求,以便显示与您访问的网站关联的图标。正在访问。我敢打赌你没有这样的文件,这就是为什么它被重写为 index.php
(因为该文件不存在)。是的,我知道......这完全是蹩脚的,尤其是当你从未听说过它的时候。
好了,现在您已经知道了一切,您可以找到解决方法:
RewriteEngine On
RewriteBase /
# Redirect "www" to "without-www" equivalent
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Don't touch existing files/folders/symlinks or a "favicon.ico" request
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} ^/favicon\.ico$ [NC]
RewriteRule ^ - [L]
# Rewrite every other url to index.php
RewriteRule ^ index.php [L]
关于PHP,htaccess : Multiple script executing when use "RewriteBase/" on vhost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384889/