首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将查询字符串转换为分段URI?

如何将查询字符串转换为分段URI?
EN

Stack Overflow用户
提问于 2013-01-14 19:16:13
回答 3查看 2.2K关注 0票数 1

我正在尝试转换查询字符串;

代码语言:javascript
运行
复制
http://atwd/books/course?course_id=CC100&format=XML&submit=Submit

转换为段URI;

代码语言:javascript
运行
复制
http://atwd/books/course/CC100/XML

我在CodeIgniter工作。

我看到了一个堆栈溢出的答案,上面说要检查CodeIgniter的URL段指南,但我不认为有任何关于如何将查询字符串转换为段URI的信息。然而,有一种方法可以将片段URI转换为查询字符串,这也带来了来自Google的大量结果。

another stackoverflow answer之后,我在我的.htaccess文件中尝试了一下,但似乎什么都不起作用

代码语言:javascript
运行
复制
RewriteCond %{QUERY_STRING} ^course_id\=([^&]+)\&format\=([^&]+)$
RewriteRule ^$ /course/%1/format/%2 [R,L]

在我的整个.htaccess文件中,我有这个;

代码语言:javascript
运行
复制
<IfModule mod_rewrite.c>
RewriteEngine on

#Source: http://codeigniter.com/user_guide/general/urls.html
#Removal of index.php
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?route/$1 [L]

#Source: https://stackoverflow.com/questions/3420204/htaccess-get-url-to-uri-segments
#Format Course function requests
RewriteBase /
RewriteCond %{QUERY_STRING} ^course_id\=([^&]+)\&format\=([^&]+)$
RewriteRule ^$ /course/%1/format/%2 [R,L]
</IfModule>

这是在我的Codeigniter screenshot根目录中

我在.htaccess文件中的代码不工作,我刷新了页面,但没有任何反应。不过,隐藏index.php的代码正在运行。有人知道为什么吗?

EN

Stack Overflow用户

发布于 2013-01-15 00:28:27

将URL从一件事转换为另一件事的概念是完全模糊的,请参阅此答案的上半部分,以了解在重定向或重写时URL会发生什么:https://stackoverflow.com/a/11711948/851273

有两件事会发生,我将大胆尝试一下,猜想你想要第二件事,因为你抱怨刷新页面没有任何作用。

在您的规则中,您将匹配一个空白URI:RewriteRule ^$ /course/%1/format/%2 [R,L]。这是你的规则不起作用的第一个原因。

您需要更正规则中的模式以匹配您希望重定向的URI,并且您需要将此规则放在您已有的路由规则之前。因此,所有内容应该大致如下所示:

代码语言:javascript
运行
复制
<IfModule mod_rewrite.c>
RewriteEngine on

RewriteBase /
RewriteCond %{QUERY_STRING} ^course_id\=([^&]+)\&format\=([^&]+)$
RewriteRule ^/?books/course$ /course/%1/format/%2 [R,L]

#Source: http://codeigniter.com/user_guide/general/urls.html
#Removal of index.php
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?route/$1 [L]

</IfModule>

首先,你需要确保你所有的链接看起来像这样:/course/CC100/format/XML。更改您的CMS或静态HTML,使所有链接都以这种方式显示。

然后,您需要更改周围的规则(在您的codeigniter路由规则之前),使其类似于以下内容:

代码语言:javascript
运行
复制
<IfModule mod_rewrite.c>
RewriteEngine on

RewriteBase /

# redirect browser to a URI without the query string
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /books/course/?\?course_id=([^&]+)&format=([^&]+)
RewriteRule ^/?books/course$ /course/%2/format/%3? [R,L]

# internally rewrite query string-less request back to one with query strings
RewriteRule ^/?course/([^/]+)/format/([^/]+)$ /books/course?course_id=$1&format=$2&submit=Submit [L]

#Source: http://codeigniter.com/user_guide/general/urls.html
#Removal of index.php
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?route/$1 [L]

</IfModule>
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14317440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档