분산형 - 서버 Nginx: Nginx 정적 리소스 구성 지침의 기본 시리즈 server_name | 수신 | 위치 | 루트 | 별칭 | 인덱스 | error_page


브라우저를 통해 HTTP 요청을 보내면 요청이 클라이언트에서 서버로 전송되어 필요한 콘텐츠를 얻고 해당 콘텐츠가 페이지에 에코되어 표시됩니다. 이때 우리가 요청하는 콘텐츠는 정적 리소스와 동적 리소스의 두 가지 유형으로 구분됩니다. 정적 리소스는 일반적인 HTML 페이지, CSS 파일, js 파일, 사진, 비디오 및 기타 리소스와 같이 실제로 서버 측에 존재하며 직접 표시할 수 있는 파일을 의미하며, 동적 리소스는 실제로 서버 측에 존재하지만 실제로는 서버 측에 존재하는 파일을 의미합니다. 특정 비즈니스 논리 처리를 거쳐 보고서 데이터 표시, 관련 특정 데이터 표시 및 현재 로그인한 사용자를 기반으로 하는 기타 리소스 표시와 같은 다양한 조건에 따라 페이지의 다른 부분을 표시해야 합니다.

Nginx가 정적 리소스의 콘텐츠를 처리할 때 다음 문제를 고려해야 합니다.

(1) 정적 리소스 구성 지침
(2) 정적 리소스 구성 최적화
(3) 정적 리소스 압축 구성 지침
(4) 정적 리소스 캐싱 처리
(5) 크로스 도메인 문제 및 안티 리칭 문제를 포함한 정적 리소스 액세스 제어

먼저 정적 리소스에 대한 구성 지침을 살펴보겠습니다.

01. server_name 명령

요청을 받으면 nginx는 먼저 요청의 호스트 이름과 포트 번호가 구성 파일에 있는 서버 블록의 수신 주소(listen)와 일치하는지 확인합니다. 일치하는 수신 주소가 발견되면 nginx는 계속해서 서버 블록의 server_name 지시문을 확인합니다. server_name 지시문은 서버 블록과 일치하는 가상 호스트 또는 IP를 지정하는 데 사용됩니다. nginx는 다음 순서로 일치합니다.

  • server_name 지시문에 특정 호스트 이름이 지정된 경우 요청된 호스트 이름이 정확히 일치해야 합니다.
  • server_name 지시문에 와일드카드 문자가 사용되는 경우 요청된 호스트 이름은 와일드카드 문자와 일치해야 합니다.
  • server_name 지시문에 정규식이 사용되는 경우 요청된 호스트 이름은 정규식과 일치해야 합니다.

요청된 호스트 이름과 일치하는 서버 블록이 발견되면 nginx는 서버 블록에 구성된 해당 위치로 요청을 전달합니다. 요청한 호스트 이름과 일치하는 서버 블록이 없으면 nginx는 기본 서버 블록을 사용하여 요청을 처리하고 기본 서버 블록이 설정되지 않은 경우 nginx는 첫 번째 서버 블록을 사용하여 요청을 처리합니다.

server_name에는 정확한 일치, 와일드카드 일치, 정규식 일치의 세 가지 구성 방법이 있습니다.

1. 정확한 일치

정확히 일치 구문:

server_name domain1.com domain2.com;
server_name 192.168.1.100;

이 중 domain1.com과 domain2.com은 가상호스트의 도메인 이름이며, 여러 개의 도메인 이름을 공백으로 구분하여 지정할 수 있습니다. 요청된 호스트 이름이 server_name에 지정된 도메인 이름과 일치하면 Nginx는 처리를 위해 요청을 이 가상 호스트에 넘겨줍니다. server_name은 도메인 이름 외에도 IP 주소를 지정할 수 있으며, 이러한 방식으로 요청된 호스트 이름이 192.168.1.100인 경우 Nginx는 처리를 위해 요청을 이 가상 호스트로 넘겨줍니다.

Hosts는 확장자가 없는 시스템 파일입니다. 이 파일의 기능은 일반적으로 사용되는 일부 URL 도메인 이름과 해당 IP 주소 사이에 연관된 "데이터베이스"를 설정하는 것입니다. 사용자가 브라우저에 로그인해야 하는 URL을 입력하면 시스템은 먼저 호스트 파일에서 해당 IP 주소 검색부터 자동으로 시작합니다. 발견되면 시스템은 즉시 해당 웹 페이지를 엽니다. 찾을 수 없으면 시스템은 IP 주소 확인을 위해 DNS 도메인 이름 확인 서버에 URL을 제출합니다. . 도메인 이름에는 특정 요금이 부과되므로 호스트 파일을 수정하여 사용할 가상 도메인 이름을 만들 수 있습니다.

# 配置hosts文件
[root@192 conf]# cat /etc/hosts
127.0.0.1 www.domain1.com
127.0.0.1 www.domain2.com

# 配置nginx.conf文件
[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    server {
        listen       8080;
        server_name  127.0.0.1;

        default_type text/plain;
        return 500 'This is a 500 request';
    }

    server {
        listen       8080;
        server_name  www.domain1.com www.domain2.com;

        default_type text/plain;
        return 444 'This is a 444 request';
    }
}

# 测试访问
[root@192 conf]# curl http://www.domain1.com:8080/
This is a 444 request

[root@192 conf]# curl http://www.domain2.com:8080/
This is a 444 request

[root@192 conf]# curl http://127.0.0.1:8080/
This is a 500 request

2. 와일드카드 매칭

Server_name은 와일드카드를 지원 *하지만 와일드카드는 도메인 이름 중간에 나타날 수 없고 첫 번째 또는 마지막 단락에만 나타날 수 있다는 점에 유의해야 합니다.

# 配置nginx.conf文件
[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server {
    
    
        listen       8080;
        server_name  127.0.0.1;

        default_type text/plain;
        return 500 'This is a 500 request';
    }

    server {
    
    
        listen       8080;
        server_name  *.com;

        default_type text/plain;
        return 444 'This is a 444 request';
    }
}

# 测试访问
[root@192 conf]# curl  http://www.domain1.com:8080/
This is a 444 request

3. 정규식 매칭

정규식은 server_name에서 사용할 수 있으며 ~정규식 문자열의 시작 태그로 사용될 수 있습니다. 일반적인 정규식:

암호 설명하다
^ 검색 문자열의 시작 부분과 일치
$ 검색 문자열의 끝과 일치
. 개행 문자를 제외한 모든 단일 문자와 일치합니다. \n
\ 다음 문자를 특수 문자로 표시하려면 문자를 이스케이프하세요.
[xyz] 문자 집합은 지정된 문자와 일치합니다.
[아즈] 문자 범위는 지정된 범위 내의 모든 문자와 일치합니다.
\w 다음 문자 AZ az 0-9 및 밑줄과 일치하며 [A-Za-z0-9_]와 동일합니다.
\디 [0-9]에 해당하는 숫자 문자 일치
{N} 정확히 n번 일치
{N,} n번 이상 일치
{n,m} 최소 n회, 최대 m회 일치
* 0회 이상, {0,}와 동일
+ 1회 이상, {1,}과 동일
? 0회 또는 1회({0,1}과 동일)
[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server {
    
    
        listen       8080;
        # 以^开头,以$结尾
        server_name  ~^www\.(\w+)\.com$;

        default_type text/plain;
        # $1 匹配的是 (\w+) 中的值
        return 444 '=====》$1 =====》';
    }
}

# 测试
[root@192 conf]# curl  http://www.domain2.com:8080/
=====》domain2 =====[root@192 conf]# curl  http://www.domain1.com:8080/
=====》domain1 =====

4. default_server 속성

Nginx에서 default_server 속성은 가상 호스트를 식별하는 데 사용되며 그 기능은 이 가상 호스트를 기본 호스트로 설정하는 것입니다. 소위 기본 호스트는 Nginx가 요청을 받았을 때 해당 서버 블록이 일치하지 않으면 기본적으로 default_server에 해당하는 가상 호스트를 사용하여 요청을 처리한다는 의미입니다. default_server가 설정되지 않은 경우 Nginx는 첫 번째 서버 블록을 사용하여 요청을 처리합니다.

① 해당 서버 블록이 일치하지 않는 경우 기본적으로 default_server에 해당하는 가상 호스트를 사용하여 요청을 처리합니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server {
    
    
        listen       8080;
        server_name  www.hh.com;

        default_type text/plain;
        return 444 'This is a 444 request';
    }
    
   server {
    
    
        listen       8080 default_server;
        server_name  www.hh.com ;

        default_type text/plain;
        return 500 'This is a 500 request';
    }
}

# 如果没有匹配到对应的 server,则会默认使用 default_server 所对应的虚拟主机来处理该请求 
[root@192 conf]# curl  http://127.0.0.1:8080/
This is a 500 request

[root@192 conf]# curl http://192.168.38.34:8080/
curl: (7) Failed connect to 192.168.38.34:8080; 没有到主机的路由

② default_server가 설정되지 않은 경우 Nginx는 첫 번째 서버를 사용하여 요청을 처리합니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server {
    
    
        listen       8080;
        server_name  www.hh.com;

        default_type text/plain;
        return 444 'This is a 444 request';
    }
    
   server {
    
    
        listen       8080;
        server_name  www.hh.com;

        default_type text/plain;
        return 500 'This is a 500 request';
    }
}

# 如果没有设置 default_server,则 Nginx 会使用第一个 server 来处理该请求 
[root@192 conf]# curl  http://127.0.0.1:8080/
This is a 444 request

5. 매칭 주문 케이스

server_name 지시문은 와일드카드와 정규식을 지원하므로 여러 서버 블록을 포함하는 구성 파일에서 이름이 여러 가상 호스트의 server_name과 성공적으로 일치할 수 있습니다. 이 경우 현재 요청을 누가 처리합니까?

① server_name이 완전 일치, 정규식 일치, 시작 부분의 와일드카드 일치, 끝 부분의 와일드카드 일치, 기본 구성인 서버 블록이 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name www.domain1.com;
        default_type text/plain;
        return 200 '精确匹配成功';
    }

    server{
    
    
        listen 8080;
        server_name ~^www\.\w+\.com$;
        default_type text/plain;
        return 200 '正则表达式匹配成功';
    }

    server{
    
    
        listen 8080;
        server_name www.domain1.*;
        default_type text/plain;
        return 200 '通配符匹配*成功';
    }

    server{
    
    
        listen 8080;
        server_name *.domain1.com;
        default_type text/plain;
        return 200 '*通配符匹配成功';
    }

    server{
    
    
        listen 8080 default_server;
        server_name _;
        default_type text/plain;
	    return 444 'default_server未找到server匹配成功';
    }
}

[root@192 conf]# curl  http://www.domain1.com:8080/
精确匹配成功

② 정규식과 일치하는 server_name, 시작 부분에 와일드카드 일치, 끝 부분에 와일드카드 일치 및 기본 구성이 있는 서버 블록이 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name ~^www\.\w+\.com$;
        default_type text/plain;
        return 200 '正则表达式匹配成功';
    }

    server{
    
    
        listen 8080;
        server_name www.domain1.*;
        default_type text/plain;
        return 200 '通配符匹配*成功';
    }

    server{
    
    
        listen 8080;
        server_name *.domain1.com;
        default_type text/plain;
        return 200 '*通配符匹配成功';
    }

    server{
    
    
        listen 8080 default_server;
        server_name _;
        default_type text/plain;
	    return 444 'default_server未找到server匹配成功';
    }
}

[root@192 conf]# curl  http://www.domain1.com:8080/
*通配符匹配成功

③ 정규 표현식과 일치하는 server_name, 끝에 와일드카드 일치 및 기본 구성이 있는 서버 블록이 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name ~^www\.\w+\.com$;
        default_type text/plain;
        return 200 '正则表达式匹配成功';
    }

    server{
    
    
        listen 8080;
        server_name www.domain1.*;
        default_type text/plain;
        return 200 '通配符匹配*成功';
    }

    server{
    
    
        listen 8080 default_server;
        server_name _;
        default_type text/plain;
	    return 444 'default_server未找到server匹配成功';
    }
}

[root@192 conf]# curl  http://www.domain1.com:8080/
通配符匹配*成功

④ server_name이 정규식 일치 및 기본 구성인 서버 블록이 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name ~^www\.\w+\.com$;
        default_type text/plain;
        return 200 '正则表达式匹配成功';
    }

    server{
    
    
        listen 8080 default_server;
        server_name _;
        default_type text/plain;
	    return 444 'default_server未找到server匹配成功';
    }
}

[root@192 conf]# curl  http://www.domain1.com:8080/
正则表达式匹配成功

⑤ 기본 구성의 서버 블록을 일치시킵니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080 default_server;
        server_name _;
        default_type text/plain;
	    return 444 'default_server未找到server匹配成功';
    }
}

[root@192 conf]# curl  http://www.domain1.com:8080/
default_server未找到server匹配成功

02. 듣기 명령

공식 문서 주소: https://nginx.org/en/docs/http/ngx_http_core_module.html#listen

Nginx에서는 Listen 지시문을 사용하여 Nginx가 수신하는 IP 주소와 포트 번호를 지정합니다. 구문은 다음과 같습니다.

listen address:port [options];

이 중 주소는 모니터링할 IP 주소를 나타내며, 특정 IP 주소일 수도 있고, 사용 가능한 모든 IP 주소를 모니터링한다는 뜻의 *와 같은 와일드카드 문자일 수도 있습니다. port는 모니터링할 포트 번호를 나타냅니다. options는 선택 사항이며 SSL/TLS 구성, HTTP/2 구성 등과 같은 몇 가지 추가 옵션을 지정하는 데 사용됩니다.

다음은 일반적인 Listen 지시문의 몇 가지 예입니다.

# 监听指定的IP和端口
listen 127.0.0.1:8000;  

# 监听指定IP的所有端口
listen 127.0.0.1;	

# 监听所有可用的 IP 地址,端口号为 8000
listen 8000;	

# 监听所有可用的 IP 地址,端口号为 80
listen *:80;

# 监听指定的 IP 地址,端口号为 8080,启用 SSL/TLS
listen 192.168.1.100:8080 ssl;

# 监听指定的 IP 地址,端口号为 443,启用 SSL/TLS 和 HTTP/2
listen 192.168.1.100:443 ssl http2;

① nginx 구성 파일 수정: 가상 호스트의 8080 포트를 수신합니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    server {
        listen       8080;
        server_name  127.0.0.1;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

② 테스트접속 : http://192.168.38.33:8080/

여기에 이미지 설명을 삽입하세요.

03. 위치 지시어

위치 지시문은 요청된 URI를 일치시키고 일치된 요청을 처리하는 방법을 지정하는 데 사용됩니다. 위치 지시문의 구문은 다음과 같습니다.

location [ = | ~ | ~* | ^~ ] uri {
    ...
}

그 중 uri는 요청된 URI와 일치하는 데 사용되는 문자열이거나 정규식일 수 있습니다. =는 정확한 일치, 대소문자 구분 일반 일치, *는 대소문자 구분 없는 일반 일치, ^~는 일반 문자열 일치를 나타냅니다. 요청이 Nginx에 도착하면 일치하는 첫 번째 지시어가 발견될 때까지 위치 지시어를 특정 순서로 하나씩 일치시킵니다. 다음은 위치 지시문의 일치 순서입니다.

① 완전 일치( =): 요청한 URL 경로가 지정된 문자열과 정확히 일치하는 경우 이 구성 블록을 사용하여 요청을 처리합니다. 예를 들어:

location = /path {
    ...
}

② 접두사 일치( ^~): 요청된 URL 경로가 지정된 문자열로 시작하는 경우 이 구성 블록을 사용하여 요청을 처리하고 다른 위치 블록 일치를 중지합니다. 예를 들어:

location ^~ /path {
    ...
}

③ 정규식 일치( ~또는 ~*): 요청된 URL 경로가 지정된 정규식과 일치하는 경우 이 구성 블록을 사용하여 요청을 처리합니다. ~대소문자를 구분함을 나타내고, ~*대소문자를 구분하지 않음을 나타냅니다. 예를 들어:

location ~ /path {
    ...
}

④ 일반 문자열 일치: 요청한 URL 경로에 지정된 문자열이 포함된 경우 이 구성 블록을 사용하여 요청을 처리합니다. 예를 들어:

location /path {
    ...
}

1. 정확히 일치(=)

요청된 URL 경로가 지정된 문자열과 정확히 일치하는 경우 이 구성 블록을 사용하여 요청이 처리됩니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name localhost;
        
        location = /path {
    
    
            default_type text/plain;
       	    return 200 'access success';
        }
    }
}

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path
access success

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path?a=zhangsan
access success

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/pathabc
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path/abc
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

2. 접두사 매칭(^~)

요청된 URL 경로가 지정된 문자열로 시작하는 경우 해당 구성 블록을 사용하여 요청이 처리되고 다른 위치 블록의 일치가 중지됩니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name localhost;
        
        location ^~ /path {
    
    
            default_type text/plain;
       	    return 200 'access success';
        }
    }
}

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path
access success

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/pathabc
access success

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path/abc
access success

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/pat
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

3. 정규식 일치(~ 또는 ~*)

요청된 URL 경로가 지정된 정규식과 일치하는 경우 이 구성 블록을 사용하여 요청을 처리합니다. ~대소문자를 구분함을 나타내고, ~*대소문자를 구분하지 않음을 나타냅니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name localhost;
        
        # 正则表达式匹配,~^ 表示后面的路径是以 "/path" 开头,\w 表示匹配一个字母或数字,$ 表示路径的结尾。
        location ~^/path\w$ {
    
    
            default_type text/plain;
       	    return 200 'access success';
        }
    }
}

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path2
access success

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/patha
access success

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/Patha
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/pathab
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path/abc
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name localhost;
        
        # 正则表达式匹配,~*^ 表示后面的路径是以 "/path" 开头,\w 表示匹配一个字母或数字,$ 表示路径的结尾。
        location ~*^/path\w$ {
    
    
            default_type text/plain;
       	    return 200 'access success';
        }
    }
}

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/patha
access success

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path1
access success

# 可以匹配
[root@192 conf]# curl  http://192.168.38.33:8080/Patha
access success

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/Path/abc
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

# 无法匹配
[root@192 conf]# curl  http://192.168.38.33:8080/path
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

4. 일반 문자열 매칭

요청된 URL 경로에 지정된 문자열이 포함되어 있으면 이 구성 블록을 사용하여 요청을 처리합니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    server{
        listen 8080;
        server_name localhost;
        
        location /path {
            default_type text/plain;
       	    return 200 'access success';
        }
    }
}

[root@192 conf]# curl  http://192.168.38.33:8080/path
access success

[root@192 conf]# curl  http://192.168.38.33:8080/path/
access success

[root@192 conf]# curl  http://192.168.38.33:8080/path/abc
access success

[root@192 conf]# curl  http://192.168.38.33:8080/path/abc/
access success

5. 매칭 주문 케이스

① 완전 일치, 접두사 일치, 정규식 일치, 일반 문자열 일치가 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location = /path {
    
    
            default_type text/plain;
       	    return 200 '精确匹配';
        }
    }

    server{
    
    
        listen 8080;
        server_name localhost;
        
        location ^~ /path {
    
    
            default_type text/plain;
       	    return 200 '前缀匹配';
        }
    }
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location ~ /path {
    
    
            default_type text/plain;
       	    return 200 '正则表达式匹配';
        }
    }
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /path {
    
    
            default_type text/plain;
       	    return 200 '普通字符串匹配';
        }
    }
}

[root@192 conf]# curl  http://192.168.38.33:8080/path
精确匹配

② 접두사 매칭, 정규식 매칭, 일반 문자열 매칭이 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;

    server{
    
    
        listen 8080;
        server_name localhost;
        
        location ^~ /path {
    
    
            default_type text/plain;
       	    return 200 '前缀匹配';
        }
    }
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location ~ /path {
    
    
            default_type text/plain;
       	    return 200 '正则表达式匹配';
        }
    }
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /path {
    
    
            default_type text/plain;
       	    return 200 '普通字符串匹配';
        }
    }
}

[root@192 conf]# curl  http://192.168.38.33:8080/path
前缀匹配

③ 정규식 매칭과 일반 문자열 매칭이 있습니다

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location ~ /path {
    
    
            default_type text/plain;
       	    return 200 '正则表达式匹配';
        }
    }
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /path {
    
    
            default_type text/plain;
       	    return 200 '普通字符串匹配';
        }
    }
}

[root@192 conf]# curl  http://192.168.38.33:8080/path
正则表达式匹配

04. 루트 명령

root 지시어는 Nginx 서버의 루트 디렉터리를 지정하는 데 사용되는 지시어입니다. Nginx 구성 파일에서 root 지시문을 사용하여 서버의 루트 디렉터리를 지정할 수 있으며 해당 구문은 다음과 같습니다.

root path;

여기서 path는 서버 루트 디렉터리의 경로입니다. 절대 경로나 상대 경로를 사용할 수 있습니다. 상대 경로를 사용하는 경우 Nginx 구성 파일의 경로를 기준으로 합니다.

/usr/local/nginx/html디렉토리 아래에 이미지 디렉토리를 생성하고 a.jpg、b.jpg디렉토리에 2개의 사진을 넣습니다.

① 상대 경로 사용:

[root@192 conf]# ls /usr/local/nginx/html/image
a.jpg  b.jpg

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /image {
    
    
            root   html;
        }
    }
}

클라이언트가 http://192.168.38.33:8080/image/b.jpg를 요청하면 /usr/local/nginx/html/image/b.jpg에 액세스합니다.

② 절대 경로 사용: 루트 처리 결과는 루트 경로 + 위치 경로, /usr/local/nginx/html/image/b.jpg 입니다.

[root@192 conf]# ls /usr/local/nginx/html/image
a.jpg  b.jpg

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /image {
    
    
            root   /usr/local/nginx/html;
        }
    }
}

클라이언트가 http://192.168.38.33:8080/image/b.jpg를 요청하면 /usr/local/nginx/html/image/b.jpg에 액세스합니다. 이는 root로 지정된 경로 + 다음으로 지정된 경로입니다. 위치.

05. 별칭 명령

alias 지시어는 URL 경로를 서버 파일 시스템의 다른 위치에 매핑합니다. 구문은 다음과 같습니다.

location /path {
    alias /new/path;
}

그 중 /path는 클라이언트가 요청한 URL 경로이고, /new/path는 서버 파일 시스템에서의 실제 경로이다. 클라이언트가 /path를 요청하면 Nginx는 이를 /new/path에 매핑하고 해당 파일이나 디렉터리를 반환합니다.

/usr/local/nginx/html해당 디렉토리 아래에 이미지 디렉토리를 생성하고 a.jpg、b.jpg해당 디렉토리에 사진 2장을 넣습니다.

[root@192 conf]# ls /usr/local/nginx/html/image
a.jpg  b.jpg

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /image {
    
    
            alias /usr/local/nginx/html;
        }
    }
}

클라이언트가 http://192.168.38.33:8080/image/b.jpg를 요청하면 404 Not Found 오류가 보고됩니다.

nginx 오류 로그를 확인하세요.

[root@192 conf]# tail -f /usr/local/nginx/logs/error.log
2023/09/03 16:07:02 [error] 91629#0: *87 open() "/usr/local/nginx/html/b.jpg" failed (2: No such file or directory), client: 192.168.38.1, server: localhost, request: "GET /image/b.jpg HTTP/1.1", host: "192.168.38.33:8080"

접속한 곳은 alias로 지정한 경로인 /usr/local/nginx/html/b.jpg임을 알 수 있으며, location으로 지정한 경로 대신 alias로 지정한 경로를 사용한다.

② 구성 파일에서 별칭으로 지정된 경로를 다시 수정합니다.

[root@192 conf]# ls /usr/local/nginx/html/image
a.jpg  b.jpg

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /image {
    
    
            alias /usr/local/nginx/html/image;
        }
    }
}

클라이언트가 http://192.168.38.33:8080/image/b.jpg를 요청하면 액세스 권한은 /usr/local/nginx/html/image/b.jpg입니다.

06. 인덱스 명령

index 지시문은 웹사이트의 시작 페이지를 설정하는 데 사용됩니다. 구문은 다음과 같습니다.

index file1 [file2 ...];

그 중 file1, file2 등은 인덱스 파일 이름으로 여러 개를 공백으로 구분하여 지정할 수 있습니다. nginx는 이러한 파일을 찾을 때까지 지정된 순서로 검색합니다. 둘 다 발견되지 않으면 403 Forbidden 오류가 반환됩니다.

[root@192 conf]# ls /usr/local/nginx/html/image
a.jpg  b.jpg

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        location /image {
    
    
            root /usr/local/nginx/html;
            index b.jpg a.jpg;
        }
    }
}

클라이언트가 http://192.168.38.33:8080/image/를 요청하면 기본 파일 b.jpg가 index 지시문을 사용하여 지정되므로 Nginx는 /usr/local/nginx/html/image/b.jpg를 다시 넣습니다. 파일. 파일이 존재하지 않으면 디렉터리 목록 또는 403 Forbidden 오류가 반환됩니다.

07. error_page 명령어

error_page 지시어는 요청을 처리하는 동안 오류가 발생할 때 서버의 동작을 정의합니다. 이 지시문은 오류 페이지를 지정된 URL 또는 로컬 파일로 리디렉션하거나 지정된 HTTP 상태 코드를 반환할 수 있습니다. 다음은 error_page 지시어의 구문입니다:

error_page code ... [=[response]] uri;

그 중 코드는 HTTP 상태 코드로, 단일 상태 코드일 수도 있고 공백으로 구분된 여러 상태 코드일 수도 있습니다. file 또는 uri는 표시할 오류 페이지의 파일 경로 또는 URL입니다.

# 将 404 错误页面重定向到 /404.html 页面
error_page 404 /404.html;

# 把所有 404、500、502、503 和 504 错误页面重定向到 /error.html 页面。
error_page 404 500 502 503 504 /error.html;

# 把所有 404 错误页面重定向到一个 403 状态码。
error_page 404 =403;

① 특정 점프 주소를 지정할 수 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server{
    
    
        listen 8080;
        server_name localhost;
        
        error_page 404 http://www.baidu.com;
    }
}

클라이언트가 http://192.168.38.33:8080/a를 요청하면 http://www.baidu.com으로 이동합니다.

② 리디렉션 주소를 지정할 수 있습니다.

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server {
    
    
        listen 8080;
        server_name localhost;
        
        # 将 404 状态码到 /50x.html 页面
        error_page 404 /50x.html;
        
        # 把所有 500 502 503 504 状态码重定向到 /50x.html 页面。
        error_page 500 502 503 504 /50x.html;
        
        error_page 404 =200 /50x.html;
        location =/50x.html{
    
    
            root html;
        }
    }
}

클라이언트 접속 http://192.168.38.33:8080/a

여기에 이미지 설명을 삽입하세요.

③ 선택적 =[response]기능은 상태 코드를 변경하는 것입니다

[root@192 conf]# cat nginx.conf
worker_processes  1;
events {
    
    
    worker_connections  1024;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
    
    server {
    
    
        listen 8080;
        server_name localhost;

        # 当返回404找不到对应的资源的时候,在浏览器上可以看到,最终返回的状态码是200
        # 这块需要注意下,编写error_page后面的内容,404后面需要加空格,200前面不能加空格
        error_page 404 =200 /50x.html;
        location =/50x.html{
    
    
            root html;
        }
    }
}

여기에 이미지 설명을 삽입하세요.

추천

출처blog.csdn.net/qq_42764468/article/details/132652998