Nginx rewrite для статического сайта — как добавить слэш в конец?

Есть вот такой конфиг:
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 (отдаёт /public_html/index.html)
example.com/foo/index.html => example.com/foo/ (отдаёт /public_html/foo/index.html)
example.com/foo.html => example.com/foo (отдаёт /public_html/foo.html)

Как сделать, чтобы в последнем варианте добавлялся слэш в конце урла?
example.com/foo.html => example.com/foo/

Почему-то, судя по поисковой выдаче, все ищут как его убрать.

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

Такая штука сваливает всё в redirect loop
  • Вопрос задан
  • 1083 просмотра
Решения вопроса 1
andrhohlov
@andrhohlov Автор вопроса
Заработало вот с таким конфигом:

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;
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@pool
rewrite (?i)^(.*)/(.*)\.html $1/$2/ permanent;
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы