robinnnnn
robinnnnn

Reputation: 1735

NGINX location rewrite URL with or without trailing slash

Currently I have this location block:

location = /events {
    rewrite ^ https://totallydifferenturl.com;
}

This successfully redirects from mywebsite/events, but I want this block to also handle mywebsite/events/.

Trying location = /events/? didn't work out.

Upvotes: 6

Views: 11382

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You need the ~ operator to enable regex matching, and since you only need to match website/events or website/events/ as full strings, you will need anchors ^ and $ around the pattern:

location ~ ^/events/?$
         ^ ^         ^ 

The ^/events/?$ pattern matches:

  • ^ - start of input
  • /events - a literal substring /events
  • /? - one or zero / symbols
  • $ - end of input.

Upvotes: 24

Related Questions