【问题标题】:Pagination and htaccess分页和 htaccess
【发布时间】:2012-10-26 01:24:05
【问题描述】:

我正在我的 htaccess 中寻找一些帮助,以便在使用分页功能时更好地处理我的网址。

目前我的 htaccess 看起来像这样:

RewriteEngine On RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule    ^([A-Za-z0-9-]+)/?$    index.php?alias=$1    [QSA,NC,L]
RewriteRule    ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$    index.php?alias=$1/$2    [QSA,NC,L]  

基本上,我有两条规则。起初我只有第二个,将所有请求定向到我的索引页面,然后我解析出 url 的一些细节以显示正确的内容。我发现它不适用于只有一个子目录的 url,例如 example.com/bars,但只有两个目录,例如 example.com/bars/bar-name,所以我在它之前添加了规则。

这对我来说非常有用。我所有的网址看起来都很棒,而且 ?alias=bars/bars-name 已完全隐藏,现在看起来像 /bars/bars-name

虽然我最近集成了一个分页 php 功能。此函数创建如下所示的 url:

example.com/bars?alias=bars&info=mysql_table_bars&page=2

基本上'info'是分页函数查询的表名,'page'是当前页。一旦我开始使用此功能,似乎“别名”也开始显示在网址中。

我希望我的分页看起来像这些示例:

example.com/bars/page/2
example.com/hotels/page/5
etc...

我需要在我的 htaccess 中添加什么来处理这种情况?另外,有没有办法简化我现有的两条规则?

【问题讨论】:

  • 呃,为什么你在 url 中显示表名?只是好奇。
  • 我猜这是分页功能的要求,所以它知道它正在处理什么数据

标签: php .htaccess pagination


【解决方案1】:

关于您的原始规则。您的条件仅适用于紧随其后的RewriteRule,因此您需要复制它们:

RewriteEngine On 
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule    ^([A-Za-z0-9-]+)/?$    index.php?alias=$1    [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule    ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$    index.php?alias=$1/$2    [QSA,NC,L]  

对于新的分页内容,首先,从查询字符串中提取数据库表名真的很糟糕,除非它们已经以某种方式得到验证(这可能是正在发生的事情)。但即便如此,这仍然是一个信息披露问题。所以你可以使用这些规则来删除它们:

# This matches the actual request when there's pagination in the query string
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/\?]+)\?alias=([^&\ ]+)&info=.*&page=([0-9]+)

# an optional sanity check, does the request URI match the "alias" param?
RewriteCond %1:%2:%3 ^(.*):\1:(.*)$

# redirect the browser to the URL with the table name removed
RewriteRule ^ /%1/page/%2? [L,R=301]

然后你需要规则在内部用查询字符串将它们重写回请求:

# rewrite it back to the query string
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([^/]+)/page/([0-9]+) /$1?alias=$1&info=mysql_table_$1&page=$2 [L]

【讨论】:

  • 感谢您的帮助!我注意到一些问题。因此,如果我正在查看结果页面并滚动到分页,然后单击任何页码,它会正确地将我带到 /page/2 或 page/5 并且确实显示了正确的页面。虽然在分页中没有设置正确的结果页面,所以我猜测需要 ?page=5 来更新它。我假设它仍然会以某种方式静默传递。
  • $_GET['page'] 确实似乎已设置,所以我将通过我的分页功能来查看问题可能是什么
  • 我能够解决我的问题。当我在那里闲逛时,我还从 url 中取出了表名,而是将其作为变量传递。再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 2020-02-11
  • 1970-01-01
  • 2016-02-21
相关资源
最近更新 更多