M1X
M1X

Reputation: 5354

nginx location zero or one trailing slash at the end of URL

location ~ ^/random/?$ {
       try_files $uri $uri/ /api/random.php;
    }

I have this rule in my nginx config file and I want to be able to call this URL like /random or /random/

The problem is that this rule allows infinte trailing slashes at the end like /random///// for ex. will also work.

Upvotes: 1

Views: 779

Answers (1)

Richard Smith
Richard Smith

Reputation: 49682

nginx uses a normalised URI when matching location directives, so multiple consecutive /s have already been reduce to a single / by the time your regular expression is tested.

You could reject multiple consecutive /s by testing the $request_uri variable, which contains the original URI together with query string (if any). For example:

if ($request_uri ~ //) { return 403; }

Upvotes: 1

Related Questions