重写规则以期待点

时间:2014-08-06 09:23:00

标签: regex apache .htaccess mod-rewrite

我在.htaccess中使用此RewriteRule

RewriteRule ^api/v1/([A-Za-z0-9-_,]+)$ api/v1/index.php?function=$1

我已经尝试了几种变体,但我无法找到将点包含在正则表达式中的方法。

这里的一些消息来源,说我可以在我的“,”之后直接包含“。”但是有些消息来源说我需要用< strong>“。”到目前为止,两者都没有工作过。

2 个答案:

答案 0 :(得分:1)

您可以在[..]内的字符类中加入点,但您的规则几乎没有问题:

  1. 连字符必须位于第一个或最后一个位置以避免逃跑。
  2. 通过包含点,您的模式也会匹配index.php,并且由于mod_rewrite在循环中运行,它会将function查询参数设为index.php。要避免这种情况,您需要RewriteCond
  3. [a-zA-Z0-9_]可以替换为[\w]
  4. 尝试此规则:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^api/v1/([\w,.-]+)/?$ api/v1/index.php?function=$1 [L,QSA,NC]
    

答案 1 :(得分:0)

似乎你只需要添加点而不必转义

当我有以下文件时:

// .htaccess

RewriteEngine On

RewriteRule ^api/v1/([A-Za-z0-9-_,.]+)$ api/v1/index.php?function=$1 [QSA]

// api/v1/index.php

<?php

var_dump($_GET['function']);

我在浏览器中运行网址http://mydomain/api/v1/something.more.something我得到以下结果:

string(24) "something.more.something"

所以整场比赛都传递给$_GET['function']

它看起来没有任何问题(正如你所看到的那样,网址内部也有点并且它正在工作)