본문 바로가기

리눅스

[draft] NGINX 특정 파일이나 디렉터리만 허용하고 나머지 요청 제한하기

NGINX 특정 파일이나 디렉터리만 허용하고 나머지 요청 제한하기

NGINX에서는 location 블록과 접근 제어 지시어(allow, deny, return)를 활용해 특정 파일 또는 디렉터리만 허용하고 나머지 모든 요청을 제한할 수 있다.

기본 개념 정리

  1. location 매칭 우선순위
  2. location = /exact (정확 매칭)
  3. location ^~ /prefix
  4. location ~ regex
  5. location / (기본)

허용할 경로를 먼저 정의하고, 차단 규칙은 가장 마지막에 둔다가 핵심 원칙

특정 파일만 허용하고 나머지는 리다이렉트

health_check.html만 허용, 나머지는 301 리다이렉트

server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

    # 헬스체크 파일만 접근 허용
    location = /health_check.html {
        access_log /var/log/nginx/elb-healthchecker-access.log main;
    }

    # 나머지 모든 요청은 외부 사이트로 리다이렉트
    location / {
        return 301 https://sangchul.kr;
    }
}

특정 디렉터리만 허용하고 나머지는 차단

/private 디렉터리만 허용

server {
    listen 80;
    server_name yourdomain.com;

    # 허용할 디렉터리
    location /private/ {
        allow all;
    }

    # 그 외 모든 요청 차단
    location / {
        deny all;
    }
}

특정 파일만 허용하고 나머지는 모두 차단

example.html만 접근 허용

server {
    listen 80;
    server_name yourdomain.com;

    # 특정 파일 허용
    location = /example.html {
        allow all;
    }

    # 그 외 모든 요청 차단
    location / {
        deny all;
    }
}

헬스체크만 허용 + 나머지 리다이렉트 + 상태 페이지 보호

default.conf 파일

vim /etc/nginx/conf.d/default.conf
server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html index.htm;

    charset utf-8;
    autoindex off;

    access_log /var/log/nginx/localhost-access.log main;
    error_log  /var/log/nginx/localhost-error.log;

    # 헬스체크 파일 허용
    location = /health_check.html {
        access_log /var/log/nginx/elb-healthchecker-access.log main;
    }

    # nginx, php-fpm 상태 페이지 (내부 접근만 허용)
    location ~ ^/(status|ping)$ {
        allow 127.0.0.1;
        allow 10.2.3.158;
        allow 10.51.91.17;
        deny all;

        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

        access_log off;
    }

    # nginx stub_status
    location /basic_status {
        stub_status on;
        allow 127.0.0.1;
        allow 10.2.3.158;
        allow 10.51.91.17;
        deny all;
        access_log off;
    }

    # 숨김 파일 차단 (.git, .env 등)
    location ~ /\.(?!well-known).* {
        deny all;
    }

    # PHP 처리
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # 나머지 모든 요청은 리다이렉트
    location / {
        return 301 https://sangchul.kr;
    }
}

이러한 방식으로 원하는 경로 또는 파일을 제외하고 모든 연결을 제한할 수 있습니다.