【问题标题】:Fix a RewriteRule - Access an ID at the end of a string separated by a Hyphen修复 RewriteRule - 访问由连字符分隔的字符串末尾的 ID
【发布时间】:2020-12-20 07:39:55
【问题描述】:

我有一个图片库,其中包含 3000 多张图片,并且还在不断增长。我访问图片的网址如下:

1.
http://example.com/gallery/image/cloud-blue-plane-hawaii-428459

or 

2.
http://example.com/gallery/image/428459

PHP 脚本在这里:

http://example.com/gallery/image.php?image=428459

所以,我需要编写一个 RewriteRule 来访问它。

我相信第二个网址的正确规则(http://example.com/gallery/image/428459 )如下:

RewriteRule ^gallery/image/(\d+|[^/]+)/?$ gallery/image.php?image=$1 [L]

当我需要为第一个 url (http://example.com/gallery/image/cloud-blue-plane-hawaii-428459) 编写规则时,我有点担心……我不知道……

有没有办法为两个网址制定一个规则?

【问题讨论】:

  • 不要使用or 将前导部分设为可选。我认为gallery/image/\D*(\d+)/?$ 是为你做的。
  • 这个解决方案几乎可以工作。如果字符串中有数字,则失败:http://example.com/gallery/image/cloud-blue-plane-99-hawaii-428459

标签: regex .htaccess mod-rewrite url-rewriting


【解决方案1】:

使用

^gallery/image/[^/]*?([0-9]+)/?$

proof

说明

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  gallery/image/           'gallery/image/'
--------------------------------------------------------------------------------
  [^/]*?                   any character except: '/' (0 or more times
                           (matching the least amount possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [0-9]+                   digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  /?                       '/' (optional (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2011-02-25
    相关资源
    最近更新 更多