![nginx: 역방향 프록시에서 특정 파일 이름(*.txt)에 대해 404를 직접 처리하는 방법은 무엇입니까?](https://linux55.com/image/170321/nginx%3A%20%EC%97%AD%EB%B0%A9%ED%96%A5%20%ED%94%84%EB%A1%9D%EC%8B%9C%EC%97%90%EC%84%9C%20%ED%8A%B9%EC%A0%95%20%ED%8C%8C%EC%9D%BC%20%EC%9D%B4%EB%A6%84(*.txt)%EC%97%90%20%EB%8C%80%ED%95%B4%20404%EB%A5%BC%20%EC%A7%81%EC%A0%91%20%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F.png)
nginx
포트 80 및 443의 프런트엔드가 nginx
TLS를 포함한 모든 외부 액세스를 처리하는 복잡한 설정이 있습니다 .
frontend-nginx에 있는 파일의 경우 /texts
요청은 CPU 및 기타 리소스를 소비하는 복잡한 프로세스에서 기존 텍스트 파일을 동적으로 수정하는 두 번째 backend-nginx로 프록시되어야 합니다.
존재하지 않는 파일 *.txt
(404)의 경우 백엔드를 전혀 방해하지 않고 기본 파일을 클라이언트에 직접 제공하고 싶습니다 /texts/default.txt
. 그러나 현재 존재하지 않는 파일은 여전히 error_page 404
백엔드 회로에서만 처리될 수 있습니다. 기존 파일을 제공하는 데 문제가 없으며 프록시가 작동합니다.
내 구성은 다음과 같습니다.
frontend-nginx.conf:
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name frontend.example.org;
root /srv/www;
location /texts/ {
location ~ \*.txt$ {
root /srv/www/backend;
####### the next line has absolutely no effect
try_files $uri /texts/default.txt;
}
proxy_pass http://localhost:90;
proxy_redirect http://localhost:90/ /;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Client-Verify SUCCESS;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_redirect off;
}
}
# https goes here, all the same except TLS
}
backend-nginx.conf:
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 127.0.0.1:90;
root /srv/www/backend;
charset utf-8;
expires -1; # no-cache
location ~ /..*\.txt$ {
# longer cache time for text files
expires 10m;
# this actually works but only here in the backend
error_page 404 @404;
}
location @404 {
return 302 $scheme://frontend.example.org/texts/default.txt
}
}
}
내 프런트엔드 구성 파일에 404 리디렉션을 처리하는 것처럼 보이는 쓸모없는 설명이 있지만 default.txt
실제로는
wget -v http://frontend.example.org/texts/notexist.txt
백엔드 내부에서만 리디렉션을 받습니다(따라서 프록싱이 발생합니다).
답변1
location /texts/ {
proxy_set_header ...;
proxy_pass ...;
location ~ \.txt$ {
root /path/to/root;
try_files $uri /texts/default.txt;
proxy_pass ...;
}
}
location = /texts/default.txt {
root /path/to/root;
}
이 명령문에 대한 올바른 정규식을 기록해 두십시오 location
. 이러한 proxy_set_header
문은 상속되지만 proxy_pass
문은 중첩된 location
.
이 try_files
명령문은 파일이 존재하는지 확인하고 존재하지 않으면 URI를 변경합니다.
기본 파일에는 location
파일을 올바른 루트 디렉터리에서 정적 파일로 사용할 수 있도록 전용 파일이 있습니다.
파일 경로는 의 값 과 URI를 root
연결하여 구성 되므로 파일은 /texts/default.txt
에 위치합니다 /path/to/root/texts/default.txt
.