Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx redirect: /*/ to /*.html (add .html to url)

i would like to add ".html" to every document ending on "/", except from the homepage.

i have tried some different ways using rewrite and return 301 with nginx but i didn´t not get it working. attached the last version i did, which is doing /*/.html but the second / should not be there.

location / {
    try_files $uri $uri/ =404;
    return 301 $scheme://$host$request_uri.html;
}

Solution im am looking for:

root: domain.com should be delivered as www.domain.com

files should be redirected (301) to the *.html version

  • domain.com/abc/ to domain.com/abc.html
  • domain.com/dir1/abc/ to domain.com/dir1/abc.html
like image 886
marketom Avatar asked Jan 27 '26 15:01

marketom


1 Answers

You will need to use a regular expression to capture the part of the URI before the trailing /, in order to eliminate it. One solution would be to use a named location with the try_files statement.

For example:

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^(.+)/$ $1.html permanent;
}

See this document for more.

like image 54
Richard Smith Avatar answered Jan 29 '26 03:01

Richard Smith