【问题标题】:Nginx get first part of URLNginx 获取 URL 的第一部分
【发布时间】:2020-10-28 13:24:11
【问题描述】:

在这种情况下,我只想获取 URL 的“user1”、“user2”部分。

site.com/user1/
site.com/user2/
site.com/user2/about
site.com/user2/contact

当我尝试这样的事情时,它会获取所有 URL。

location ~* ^/(.*)$ {
  add_header X-username $1
  # configuration
}

那么如何更改正则表达式以仅获取 URL 的第一部分?

【问题讨论】:

  • 试试:^/([^/]+)/
  • 这看起来像工作。谢谢。

标签: regex nginx url server


【解决方案1】:

使用

^/([^/]+)

proof

说明

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  /                        '/'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [^/]+                    any character except: '/' (1 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多