Complete the code to redirect URLs ending with a slash to the same URL without the slash.
rewrite ^(.+)/$ [1] permanent;The rewrite directive uses $1 to capture the URL without the trailing slash and redirects permanently.
Complete the code to redirect URLs without a trailing slash to the same URL with a slash.
rewrite ^(.+[^/])$ [1] permanent;The rewrite adds a trailing slash by appending / to the captured URL $1.
Fix the error in the location block to normalize trailing slashes by redirecting URLs ending with a slash to without slash.
location / {
if ($request_uri ~ [1]) {
return 301 $scheme://$host$1;
}
}The regex ^(.+)/$ matches URLs ending with a slash and captures the part before it in $1 for redirection.
Fill both blanks to create a map that normalizes URLs by removing trailing slashes except for root.
map $request_uri $normalized_uri {
default [1];
~^(.+)/$ [2];
}The map keeps the original URI by default and removes trailing slashes by capturing the part before the slash in $1.
Fill all three blanks to rewrite URLs to normalized form and redirect permanently.
server {
listen 80;
server_name example.com;
map $request_uri $normalized_uri {
default [1];
~^(.+)/$ [2];
}
location / {
if ($request_uri != [3]) {
return 301 $scheme://$host$normalized_uri;
}
}
}The map sets default to $request_uri, removes trailing slash with $1, and the if condition compares $request_uri with $normalized_uri to redirect.