【问题标题】:Using question mark in CodeIgniter routing在 CodeIgniter 路由中使用问号
【发布时间】:2012-04-09 13:45:35
【问题描述】:

我需要改变

http://mysite.com/profile?username=nick

http://mysite.com/user/nick

使用 CodeIgniter 路由。我将以下行添加到routes.php,但它不起作用:

$route['user/(:any)'] = "profile?username=$1";

这是我使用的.htaccess 文件:

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
AddDefaultCharset utf-8

我该如何解决这个问题?提前致谢。

编辑:

我的意思是 URL 结构发生变化。所以在路由之后它必须重定向

http://mysite.com/user/nick

http://mysite.com/profile?username=nick

【问题讨论】:

    标签: php regex codeigniter routing wildcard


    【解决方案1】:

    处理重定向的 Htaccess 规则:

    RewriteRule user/([^/?]+) /profile?username=$1 [L,R=301]
    

    Route.php 更改:

    <?php
    $route['profile'] = 'profile/index';
    

    配置文件控制器:

    <?php
    class Profile extends CI_Controller {
    
        public function index()
        {
            $username = $this->input->get('username');
            // do lookup based on username
        }
    }
    

    但是:这种重定向只有在你有很多没有意义的缓存链接改变时才有意义。从您的问题看来,您可能混淆了路由和重定向的概念。


    编辑:要“路由”(而不是“重定向”),步骤如下:

    内部重新路由请求的 Htaccess 规则:

    RewriteRule /profile?username=([^&]*) index.php/user/$1 [L]
    

    Route.php:

    <?php
    $route['user/(:any)'] = 'user/index/$1';
    

    控制器:

    <?php
    class User extends CI_Controller {
        public function index($username)
        {
            // ...
        }
    }
    

    如果这不起作用,那么,那么,你在解释你的问题时做得很糟糕:)。

    【讨论】:

    • 当你的意思是“路线”时使用“重定向”这个词会使每个答案都与你想要的完全相反。我会编辑它。
    【解决方案2】:

    最有可能的问题是? 是正则表达式语言中的一个特殊字符,表示 1 或 0。您需要对其进行转义以使其匹配,这样应该可以解决您的问题: $route['user/(:any)'] = "profile\?username=$1";

    【讨论】:

      【解决方案3】:

      好的,你想反其道而行之。试试:

      RewriteRule user/([^/?]+) index.php/profile?username=$1 [L]
      

      对不起,如果这不起作用,我的 Apache 不合作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-16
        • 2012-04-27
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 1970-01-01
        相关资源
        最近更新 更多