Nginx get first part of URL

Viewed 2147

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?

1 Answers

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
Related