Bart Huisman
Bart Huisman

Reputation: 125

regex nginx remove trailing slashes not apply to 2 folders?

We want nginx to permanent redirect url's with a trailing slash to the non slash url. we found: https://www.scalescale.com/tips/nginx/nginx-remove-trailing-slash/

So we put:

rewrite ^/(.*)/$ /$ permanent;

In the nginx, but the problem is it must not apply to some folders. so we found: remove trailing slash in nginx with some certain cases ignored

and we changed it to:

rewrite ^/(?!admin)(.*)/$ /$ permanent;

but then the server wouldn't start:

invalid number of arguments in "rewrite" directive in /opt/www/folder/.nginx:5

And: we want 2 folders excluded. What is the right regex to exclude the folders from the rewrite rule?

Thanks,

Bart

Edit for who comes here by google:

The answer works... only strange thing is that the standard worked without the $1 :

rewrite ^/(.*)/$ /$ permanent;

and now we made the exclude, it didn't work anymore without the $1.... but this works for now:

# remove trailing slashes
rewrite ^/(?!folder1|folder2)(.*)/$ /$1 permanent;

Upvotes: 0

Views: 1466

Answers (1)

Jon
Jon

Reputation: 3671

I suspect this is just a typo. That /$ looks like it should be /$1:

rewrite ^/(?!admin)(.*)/$ /$1 permanent;

If you have more that one URI to exclude, try something like

rewrite ^/(?!admin|secure|raw)(.*)/$ /$1 permanent;

nginx uses the same regular expression library as Perl, so you can test this stuff from a command line with

perl -ple 's#^/(?!admin|secure|raw)(.*)/$#/$1#'

and just typing in example URIs.

Upvotes: 2

Related Questions