1

我正在尝试使用名称作为 url,例如 stackoverflow。我有一个 godaddy linux 主机,并且正在使用 .htaccess 来控制 mod_rewrite url。

我正在尝试获得以下信息:

  • /about => about.php
  • /schools/add => add-school.php
  • /api/questions/ask => /questions.php?action=ask
  • /api/questions/158 => /questions.php?action=get&id=158
  • /api/questions/144/points => /questions.php?action=get-points&id=144

这是我到目前为止所拥有的,但它不起作用:

## Mod rewrite manual: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
<IfModule mod_rewrite.c>
  RewriteEngine On

  # try the corresponding php file
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ([A-Za-z0-9_-]+) $1.php [qsa]

  # special cases
  RewriteRule ^schools\/add$ add-school.php

  # API
  RewriteRule ^api\/questions\/ask$ "api.php?action=ask" [qsa]
  RewriteRule ^api\/questions\/(\d+)$ "api.php?action=get&id=$1" [qsa]
  RewriteRule ^api\/questions\/(\d+)\/points$ "api.php?action=get-points&id=$1" [qsa]

</IfModule>
4

2 回答 2

1

所以你的第一个 RewriteRule 正在接管。当您去学校/添加并且该文件不存在时,它会将您重定向到也不存在的schools.php,因此您只需要重新排序它们,当我们在它时删除转义:

## Mod rewrite manual: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
<IfModule mod_rewrite.c>
  RewriteEngine On

  # special cases
  RewriteRule ^schools/add$ add-school.php

  # API
  RewriteRule ^api/questions/ask$ api.php?action=ask [qsa]
  RewriteRule ^api/questions/(d+)$ api.php?action=get&id=$1 [qsa]
  RewriteRule ^api/questions/(d+)/points$ api.php?action=get-points&id=$1 [qsa]


  # try the corresponding php file
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ([A-Za-z0-9_-]+) $1.php [qsa]
</IfModule>
于 2013-06-23T05:33:15.037 回答
1

您的代码中几乎没有错误:

  1. 重写规则的顺序非常重要。您应该始终从最具体的到最通用的排序。请记住,通用的可以匹配特定规则的模式并覆盖那些特殊情况。
  2. L始终用(last)标记单个规则的结束。
  3. 将请求转发给.php您需要确保该 php 文件确实存在。

这些建议是您修改后的代码:

Options +FollowSymLinks -MultiViews

<IfModule mod_rewrite.c>
  # Turn mod_rewrite on
  RewriteEngine On
  RewriteBase /

  # special cases
  RewriteRule ^schools/add/?$ /add-school.php [L,NC]

  # API
  RewriteRule ^api/questions/ask/?$ /api.php?action=ask [L,QSA,NC]
  RewriteRule ^api/questions/(d+)/points/?$ /api.php?action=get-points&id=$1 [L,QSA,NC]
  RewriteRule ^api/questions/(d+)/?$ /api.php?action=get&id=$1 [L,QSA,NC]

  # try the corresponding php file if it exists
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{DOCUMENT_ROOT}/$1.php -f
  RewriteRule ^(.+?)/?$ $1.php [L]
</IfModule>
于 2013-06-23T06:13:00.763 回答