简体   繁体   中英

Nginx get first part of URL

In this context I'd like to get only "user1", "user2" parts of the URLs.

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

When I try something like this, it gets all the URL.

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

So how can I change the regex to get only first part of the URL?

Use

^/([^/]+)

See proof .

Explanation

--------------------------------------------------------------------------------
  ^                        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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM