Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
robinnnnn Avatar asked Nov 30 '22 23:11

robinnnnn


1 Answers

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.
like image 81
Wiktor Stribiżew Avatar answered Dec 05 '22 08:12

Wiktor Stribiżew