NGINX Add or Remove "/" from URLs

1. Add

Nginx
1
rewrite ^(.*[^/])$ $1/ permanent;

Possible problems: Adding / to static resources such as pictures results in 404

Solution: change to

Nginx
1
2
3
if ($uri !~ ".*\.(gif|jpg|jpeg|png|bmp|swf|js|css)") {
     rewrite ^(.*[^/])$ $1/ permanent;
}

Possible problems:

Conflicts with other pseudo-static rules, causing redirection to /index.php/...

There is no solution at present, you can try to modify the position where this line of code is placed.

2. Remove

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

3. Precautions

NGINX will add slashes by default, generally do not change them randomly.

Possible application scenarios:

The program supports both with and without slashes, for example:

/thread/1
/thread/1/

Both can be accessed, then there is a high probability that search engines will index both, resulting in decentralization.

Well, it's best to redirect one of the 301s to the default one.

Finally, be careful not to use

Nginx
1
2
3
location {
     ...
}

Bracketing may lead to failure, which is related to the priority of NGINX pseudo-static rules, so I won’t go into details here.

refer to

Nginx Rewrite Rules Guide
http://www.ttlsa.com/nginx/nginx-rewriting-rules-guide/

NGINX Add or Remove "/" from URLs

https://blog.tsinbei.com/en/archives/683/

Author
Hsukqi Lee
Posted on

2023-05-18

Edited on

2023-05-18

Licensed under

CC BY-NC-ND 4.0

Comments

Name
Mail
Site
None yet