我的根目录下有以下。htaccess文件:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !('.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
这是删除URL中的.php扩展名(例如。www.example.com/about或www.example.com/about/,但仍在加载页面(www.example.com/about.php)。到目前为止,我需要对我的HTML进行的唯一更改是在每个href
或src
的前面包含一个../
。
现在我在PHP登录脚本的末尾使用了以下代码:
header("Location: ../dashboard/");
应该带我到www.example.com/dashboard.php,但却抛出以下错误:
The requested URL /example.com/dashboard.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
文件肯定上传了。我的。htaccess是否有任何问题,导致header()
行为不正确?
编辑
如果我把这一行改成:
header("Location: ../dashboard.php");
那么它工作,但我真的不希望在URL中的文件扩展名
修改规则,在重写之前检查.php
文件是否存在:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !('.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
RewriteRule ^([^/]+)/$ $1.php [L]
RewriteCond %{DOCUMENT_ROOT}/$1/$2.php -f [NC]
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php [L]
在.htaccess文件中试试
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www'.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L]
</IfModule>
对于标题重定向,只需这样做:
header("location: ../dashboard")
不带尾斜杠(/)
我找到我的问题了。这是一个简单的用户错误。
我工作的目录不是真正的根目录。这是同一个账户托管下的一个域名。所以我实际上在root/example.com/dashboard.php
中,而。htaccess文件在root/.htaccess
中。复制。htaccess文件到root/example.com/
修复了我的问题。