给定太多参数时,RewriteRule触发器404

时间:2014-01-17 03:15:38

标签: php regex apache .htaccess mod-rewrite

我现在正在建设的网站由两个主要部分组成:一般公众可以访问的一方,以及只授权人员可以访问的管理方。

它使用基本模板构建,以便按以下方式访问不同的部分(使用RewriteRules)。

公开: http://localhost/about应改写为http://localhost/index.php?page=about

管理: http://localhost/admin/manage-users应改写为http://localhost/admin/index.php?page=manage-users

所有网址只有一个参数。也就是说,public将始终是localhost / PAGE,admin将始终是localhost / admin / PAGE。

目前,我有以下.htaccess文件:

RewriteEngine on

RewriteRule ^admin/([^/.]+)/?$ /admin/index.php?page=$1 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [L,NC]

在正确构造URL时,这似乎可以正常工作。例如,如果我导航到localhost/aboutlocalhost/admin/manage-users两个页面都正确加载。但是,如果我转到localhost/about/blahlocalhost/admin/manage-users/blah,页面会加载,但CSS不存在。看看Chrome中的开发人员工具,看来这是因为它试图分别从目录localhost/about/css/localhost/admin/css/加载CSS文件,因为样式表链接到具有亲戚的页面路径。 (实际上,localhost/css/是它实际所在的目录。)

因此,即使RedirectRule忽略了URL中的任何额外参数,它也会尝试加载相对于URL中提供的最后一个“目录”的相对路径。

有没有办法完全忽略任何额外的../..参数?或者,更好的是,当提供的参数太多时触发404?

更新:我刚刚发现这个问题实际上比我之前想象的要复杂得多。因为我的页面只有虚拟数据来测试模板文件,所以直到现在我才注意到它。

当您导航到localhost/adminlocalhost/admin/manage-users时,它会从http://localhost/admin/index.php文件加载,但导航到localhost/admin/manage-users/blah时会恢复为加载http://localhost/index.php {1}}文件。这让我觉得我需要在RewriteRule中改变一些东西,虽然我不知道是什么。

2 个答案:

答案 0 :(得分:1)

从长远来看,在css,js,images文件而不是相对文件中使用绝对路径会更好。这意味着您必须确保这些文件的路径以http://或斜杠/开头。

但为了避免对您的网站进行大规模更改,您可以使用这些规则来修复您的css / js / images链接:

RewriteEngine on

# fix CSS/js/images links
RewriteRule (?:^|/)((?:css|js|images)/.+)$ /$1 [L,R=301]

RewriteRule ^admin/([^.]+)/?$ /admin/index.php?page=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php?page=$1 [L,QSA]

不要忘记将第一条规则替换为实际的css / js / images目录。

答案 1 :(得分:0)

您需要将所有链接设为绝对网址(例如href="/css/style.css"),或者在页面标题中添加相对网址:

<base href="/" />