Home > Net >  How to redirect URLs with a trailing slash to the non-slash variant (with exceptions)?
How to redirect URLs with a trailing slash to the non-slash variant (with exceptions)?

Time:11-23

I have a few problems to set up NGINX so that all URLs with a trailing slash (/) redirect permanently to the variant without a slash. The problem is that this directive should happen for all URLs except those that start with /backend.

For example:

https://example.com/service/ --> https://example.com/service
https://example.com/service/one/ --> https://example.com/service/one
https://example.com/backend/ --> https://example.com/backend/ (should not redirect)

I am currently using this directive:

server {
    listen 80;
    listen 443 ssl http2;

    [...]

    location ~ ^/(?!backend)(. )/$ {
        return 301 $1$is_args$args;
    }

    [...]
}

unfortunately the following error occurs here:

https://example.com/service/ --> https://example.com/service/service

Can someone help me solve this regex mystery?

CodePudding user response:

Your return 301 $1$is_args$args; expression is missing a leading / so that the browser interprets the redirect as relative to the current URI. service relative to /service/ is /service/service.

Either capture the leading / in $1 or add it explicitly to the return statement.

For example:

location ~ ^/(?!backend)(. )/$ {
    return 301 /$1$is_args$args;
}
  • Related