Daniel Luca CleanUnicorn
Daniel Luca CleanUnicorn

Reputation: 1097

Nginx rewrite with and without trailing slash

I'm trying to create a set of rules that match a url with and without a trailing slash

Most of the answers were pointing me to use something similar to this.

location /node/file/ {                                                                                         
    rewrite ^/node/file/(.*)/(.*)$ /php/node-file.php?file=$1&name=$2;                                    
    rewrite ^/node/file/(.*)/(.*)/?$ /php/node-file.php?file=$1&name=$2;                                   │
}   

But this does not match the trailing slash url.

How can I write a rule that matches urls that look like

http://example.com/node/file/abcd/1234/
http://example.com/node/file/abcd/1234

Upvotes: 1

Views: 1621

Answers (1)

Richard Smith
Richard Smith

Reputation: 49682

The first rewrite statement includes (.*) as the last capture, which will match any string, including one with a trailing slash.

Use the character class [^/] to match any character except the /:

rewrite ^/node/file/([^/]*)/([^/]*)$ /php/node-file.php?file=$1&name=$2;                                    
rewrite ^/node/file/([^/]*)/([^/]*)/?$ /php/node-file.php?file=$1&name=$2;

Now you will notice that the first rewrite statement is unnecessary, as the second rewrite statement matches URIs both with and without a trailing /.

So all you need is:

rewrite ^/node/file/([^/]*)/([^/]*)/?$ /php/node-file.php?file=$1&name=$2;

Upvotes: 1

Related Questions