【问题标题】:How to use htaccess to do this?如何使用 htaccess 来做到这一点?
【发布时间】:2013-10-14 15:48:48
【问题描述】:

我在这里卡住了,我正在努力弄清楚为什么它不起作用!

这是想让网址看起来像

 example.com/news/top/

来自

 example.com/index.php?view=news&task=top

但我需要这样,“任务”可以是不同的东西

 example.com/index.php?view=news&task=newest
 example.com/index.php?view=news&task=help
 example.com/index.php?view=news&task=write
 ....

当前的 .htaccess 看起来像:

DirectoryIndex index.php
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/([^/\.]+) index.php?view=$1&task=$2

如果我访问 www.example.com/news/ -> 它只加载 index.php 但不通过 ?view=news

如果我访问 www.example.com/news/top/ -> 效果很好。

但我需要它们都工作,向 .htaccess 添加一个新行,例如:

RewriteRule ^news/ index.php?view=news

然后访问 www.example.com/news/ 工作正常,但访问 www.example.com/news/top/ 将无法获得任务的价值。

请帮帮我!

提前谢谢你。

【问题讨论】:

  • RewriteRule ^news/top/index.php?task=news&task=$1 [L] 但这不起作用
  • 看来您正在选择 RESTful 架构。阅读 MVC 模式,您将对路由这些请求有一个很好的了解。这可能会有所帮助:lornajane.net/posts/2012/…

标签: php .htaccess url rewrite


【解决方案1】:

尝试将这些规则添加到文档根目录中的 htaccess 文件中:

RewriteEngine On

# Redirect access to index.php
RewriteCond %{THE_REQUEST} \ /index\.php\?view=([^&]+)&task=([^&\ ]+)
RewriteRule ^ /%1/%2/? [L,R=301]

# rewrite to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?view=$1&task=$2 [L]

第一个将/index.php?view=news&task=foo 之类的请求重定向到/news/foo/。然后第二条规则在内部将/news/foo/ 之类的请求重写回/index.php?view=news&task=foo

如果您的所有链接都已经看起来像 /news/foo/,那么您将不需要第一条规则。

【讨论】:

    【解决方案2】:

    我不是 htaccess 的老手,但这样的事情可能会奏效:

    RewriteRule /news/(.*) /index.php?view=news&task=$1 [L]
    

    这应该将所有对 /news/abc 的请求重写为 index.php?task=news&view=abc。反向引用 $1 代表 RegEx 中被括号括起来的第一个模式。

    【讨论】:

    • 老是说不能从url获取“任务”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多