3

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Was going to ask a similar question but then found this. If anyone is looking for rewriting links that don't have the ".html" part at the end of the url you can use this, just remove / from the rewrite. like so: rewrite ^(.+)$ $1.html permanent; This way if someone tries to go to example.com/contact they will get to example.com/html instead of 404.
@ZN13 appending .html can be handled by try_files directly, for example: try_files $uri $uri.html $uri/ =404;. See the link in my answer for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.