【问题标题】:Htaccess rule to make urls like this ?page=1 look like /page/1 in CodeigniterHtaccess 规则使这样的 ?page=1 在 Codeigniter 中看起来像 /page/1
【发布时间】:2012-04-25 10:01:03
【问题描述】:

这是我的网址目前的样子:

http://mysite.com/?page=1

我怎样才能做到这一点?:

http://mysite.com/page/1

StackOverflow 上有一个post 提出了同样的问题。但是公认的解决方案对我不起作用。因为我正在使用 Codeigniter 并且我的页面导致 404 可能是因为 CI 网站的 url 模式是:

域/控制器/方法

系统假设我正在请求一个名为“page”的控制器和一个名为“1”的方法,这两者当然都不存在。或者也许是由于与我的 htaccess 文件中的其他代码冲突(我从 CI wiki 下载的,它摆脱了 index.php 并做了一些安全事情)。这是我的整个 htaccess 文件:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    #Removes access to the system folder by users. Additionally this will allow you to create a System.php controller, 'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder. This snippet prevents user access to the application folder. Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file, such as an image or css document, if this isn't true it sends the request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

#Pretty urls for pagination links
RewriteRule (.*) index.php?page=$1

</IfModule>

非缩进位是我从其他对我不起作用的 SO 问题中得到的解决方案。

此 CI 分页问题的任何解决方案?


更新

好的,阅读一些文档,现在我有这个工作:

http://mysite.com/home/index/2

htaccess 规则是什么?:

http://mysite.com/page/2

【问题讨论】:

    标签: .htaccess codeigniter url mod-rewrite friendly-url


    【解决方案1】:

    您应该在/application/config/routes.php 进行此配置(并让.htaccess 只是为了隐藏 index.php,就像您已经在做的那样)。

    $route['page/(:any)'] = 'home/index/$1';
    

    或者更好,就像记得的@zaherg(确保只有数字可以匹配):

    $route['page/(:num)'] = 'home/index/$1';
    

    这样对http://mysite.com/page/2 的所有请求都将在内部被视为http://mysite.com/home/index/2 等等。

    我建议你看看CodeIgniter User Guide - URI RoutingCodeIgniter User Guide - Tutorial − Introduction

    祝你好运。

    【讨论】:

    • 如果有人偶然发现正在执行的实际文件,CI 不会执行 301,对吗?
    • 但如果您使用(:num) 会更好,这将匹配仅包含数字的段。所以你的路线将是$route['page/(:num)'] = 'home/index/$1';
    【解决方案2】:
    RewriteEngine on
    RewriteCond $1 !^(index\.php|images|robots\.txt)
    RewriteRule ^(.*)$ /index.php/$1 [L]
    

    来自CodeIgniter docs

    这将处理删除index.php,但之后会发生什么取决于如何设置 CodeIgniter 的查询字符串处理:它可以配置为使用查询字符串而不是路径。有关详细信息,请参阅链接。

    【讨论】:

      猜你喜欢
      • 2014-10-03
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多