nginx가있는 URL에서 후행 슬래시 제거


14

내 사이트의 다음 URL이 동일해야합니다.

/foo/bar
/foo/bar/
/foo/bar/index.html

또한 두 번째 두 양식이 첫 번째 양식으로 HTTP 301 리디렉션을 발행하고 싶습니다. 나는 단지 정적 페이지를 제공하고 있으며 세 번째 양식에 따라 정렬됩니다. 즉, 사용자가 요청 /foo/bar하면에 파일을 받아야합니다 /usr/share/.../foo/bar/index.html.

내 nginx.conf현재는 다음을 포함합니다 :

rewrite ^(.+)/$ $1 permanent;
index index.html;
try_files $uri $uri/index.html =404;

이것은에 대한 요청에 대해 작동 /foo/bar/index.html하지만 Safari에서 요청 /foo/bar하거나 /foo/bar/Safari가“리디렉션이 너무 많이 발생했습니다”라고 말하면 무한 리다이렉트 루프 또는 이와 유사한 것으로 가정합니다. 설명 된 방식으로 nginx가 URL을 파일에 매핑하도록하려면 어떻게해야합니까?

편집 : 내 전체 구성

여기 nginx.conf내 도메인 이름이 "example.com"으로 바뀐 내 전체 가 있습니다.

user www-data;
worker_processes 1;
pid /run/nginx.pid;

events {
  worker_connections 768;
}

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  server_tokens off;

  server_names_hash_bucket_size 64;

  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;

  gzip on;
  gzip_disable "msie6";
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_http_version 1.1;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss application/atom+xml text/javascript image/svg+xml;

  server {
    server_name www.example.com;
    listen 80;
    return 301 $scheme://example.com$request_uri;
  }

  server {
    server_name example.com 123.45.67.89 localhost;
    listen 80 default_server;

    # Redirect /foobar/ to /foobar
    rewrite ^(.+)/$ $1 permanent;

    root /usr/share/nginx/www/example.com;
    index index.html;
    try_files $uri $uri/index.html =404;

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
      root /usr/share/nginx/html;
    }
  }
}

이 파일들이 실제로 파일 시스템에 존재합니까?
— Michael Hampton

@MichaelHampton 네. 에 대한 요청 /foo/bar/index.html은 파일을 /usr/share/nginx/www/foo/bar/index.html설정하거나 설정 한 파일을 반환해야 합니다. 웹 사이트의 모든 경로는 파일 시스템 경로와 직접 일치합니다.
— bdesham

@bdesham 나는 재생할 수 없습니다. 여기 내가 당신의 구성 paste.ubuntu.com/7501697로 얻는 것
— Alexey Ten

@AlexeyTen 당신이 뭔가 다른 것을 얻는 것이 이상합니다. 조사해 주셔서 감사합니다. 나는 나를 위해 일한 구성을 게시했습니다.
— bdesham

답변:


19

이 정규식을 server블록 에 사용하십시오 .

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

모든 후행 슬래시 URL을 각각의 비 후행 슬래시로 리디렉션합니다.


1
이것은 질문의 일부만을 다룹니다.
— bdesham

5
이것은 질문의 전체 제목을 다룹니다.
— Jivan

5

server구성에서 마지막 블록으로 이것을 사용하여 원하는 동작을 얻을 수있었습니다 .

server {
  server_name example.com 123.45.67.89 localhost;
  listen 80 default_server;

  # Redirect /foobar/ and /foobar/index.html to /foobar
  rewrite ^(.+)/+$ $1 permanent;
  rewrite ^(.+)/index.html$ $1 permanent;

  root /usr/share/nginx/www/example.com;
  index index.html;
  try_files $uri $uri/index.html =404;

  error_page 404 /404.html;
  error_page 500 502 503 504 /50x.html;

  location = /50x.html {
    root /usr/share/nginx/html;
  }
}

이것은 나를 위해 작동하지 않는 것 같습니다 /index.html-URL은 리디렉션 대신 HTTP 200으로 응답됩니다. "다시 쓰기"줄은 무시됩니다. 여전히 최신 상태입니까?
— Christoph Burschka

1

다시 쓰지 마십시오.

  location ~ (?<no_slash>.*)/$ {
       return 301 $scheme://$host$no_slash;
  }

다시 쓰기가 좋은 생각이 아닌 이유를 확장 할 수 있습니까?
— bdesham


귀하의 링크가 재 작성을 피하도록 제안하는 이유는 의도하지 않은 부작용을 일으킬 수 있기 때문에 가독성을 향상시키기위한 것입니다. 귀하의 답변은rewrite ^(.+)/+$ $1 permanent;
— chrBrd

1
이것은 좋은 대답입니다. 왜 다운 다운되었는지 모르겠습니다. 이 기사 에는 왜 " rewrite나쁜 이유"를 설명하는 "세금 재 작성"이라는 제목 이 있습니다. 제공된 답변은 URI를 캡처하고 일치시킵니다. 성능을 향상 시킬지 확실하지 않으면 테스트가 필요합니다. (?<no_slash>.+)/$대신 이 정규식을 사용 하여 홈 페이지를 리디렉션하지 마십시오.
— 면도기

0
if ($request_uri ~ (.*?\/)(\/+)$ ) {
return 301 $scheme://$host$1;
}

이 규칙은 임의의 수의 슬래시를 처리하며 URL을 유지합니다. 또한 기본 URL 후행 슬래시도 처리합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.