A
A
Andrey Khokhlov2017-12-15 08:32:45
PostgreSQL
Andrey Khokhlov, 2017-12-15 08:32:45

Nginx rewrite for a static site - how to add a slash to the end?

There is this config:

server {
    listen 80;
    server_name _;

    root /public_html;
    index index.html;

    # remove multiple slashes
    if ($request_uri ~ "^[^?]*?//") {
        rewrite "^" $scheme://$host$uri permanent;
    }

    # drop html extension

    if (!-f "${request_filename}index.html") {
        rewrite ^/(.*)/$ /$1 permanent;
    }

    if ($request_uri ~* "/index.html") {
        rewrite (?i)^(.*)index\.html$ $1 permanent;
    }

    if ($request_uri ~* ".html") {
        rewrite (?i)^(.*)/(.*)\.html $1/$2 permanent;
    }

    location / {
        try_files $uri.html $uri $uri/ =404;
    }
}

example.com/index.html => example.com(returns /public_html/index.html)
example.com/foo/index.html => example.com/foo/(returns /public_html/foo/index.html)
example.com/foo.html => example.com/foo(returns /public_html/foo.html)
How to add a slash at the end of the url in the last option?
example.com/foo.html => example.com/foo/
For some reason, judging by the search results, everyone is looking for how to remove it.
rewrite ^([^.]*[^/])$ $1/ permanent;
Such a thing dumps everything in a redirect loop

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Khokhlov, 2017-12-16
@andrhohlov

It worked with this config:

server {
    listen 80;
    server_name _;
    root /home/user/www/example.com/public_html;
    index index.html;

    # example.com/foo// => example.com/foo/
    if ($request_uri ~ "^[^?]*?//") {
      rewrite "^" $scheme://$host$uri permanent;
    }

    # example.com/index.html => example.com/
    rewrite (?i)^(.*)index\.html$ $1/ permanent;

    # example.com/foo => example.com/foo/
    rewrite ^([^.]*[^/])$ $1/ permanent;

    # example.com/foo.html => example.com/foo/
    rewrite (?i)^(.*)/(.*)\.html $1/$2/ permanent;

    # prevent access from example.com/index/
    location ~ /index/ {
        return 404;
    }

    location / {
        # remove slash from url end for access .html files
        # example.com/foo/ => example.com/foo
        rewrite ^/(.*)/$ /$1 last;
        try_files $uri.html $uri $uri/index.html $uri/ =404;
    }
}

P
pool, 2017-12-15
@pool

rewrite (?i)^(.*)/(.*)\.html $1/$2/ permanent;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question