목차
구성 시작, 중지 및 다시 로드
구성 파일의 구조
Serving Static Content
Setting Up a Simple Proxy Server
Setting Up FastCGI Proxying
백엔드 개발 PHP 튜토리얼 Nginx: 초보자 가이드

Nginx: 초보자 가이드

Aug 08, 2016 am 09:22 AM
nbsp nginx server the

이 가이드에서는 nginx에 대한 기본 소개를 제공하고 nginx로 수행할 수 있는 몇 가지 간단한 작업을 설명합니다. nginx가 이미 리더의 컴퓨터에 설치되어 있다고 가정합니다. 그렇지 않은 경우 설치를 참조하세요. nginx 페이지입니다. 이 가이드에서는 nginx를 시작 및 중지하고 해당 구성을 다시 로드하는 방법, 구성 파일의 구조를 설명하고 정적 콘텐츠를 제공하기 위해 nginx를 설정하는 방법, nginx를 프록시 서버로 구성하는 방법 및 방법을 설명합니다. FastCGI 애플리케이션과 연결합니다.

nginx에는 하나의 마스터 프로세스와 여러 개의 작업자 프로세스가 있습니다. 마스터 프로세스의 주요 목적은 구성을 읽고 평가하며 작업자 프로세스를 유지 관리하는 것입니다. 작업자 프로세스는 요청을 실제로 처리합니다. nginx는 이벤트 기반 모델과 OS 종속을 사용합니다. 작업자 프로세스 간에 요청을 효율적으로 배포하는 메커니즘입니다. 작업자 프로세스 수는 구성 파일에 정의되어 있으며 특정 구성에 대해 고정되거나 사용 가능한 CPU 코어 수에 따라 자동으로 조정될 수 있습니다(worker_processes 참조).

nginx와 해당 모듈의 작동 방식은 다음에서 결정됩니다. 구성 파일. 기본적으로 구성 파일의 이름은 nginx.conf이며 /usr/local/nginx/conf, /etc/nginx 또는 /usr/local/etc/nginx 디렉터리에 저장됩니다.

구성 시작, 중지 및 다시 로드

nginx를 시작하려면 실행 파일을 실행하세요. nginx가 시작되면 -s 매개변수로 실행 파일을 호출하여 제어할 수 있습니다. 다음 구문을 사용하세요.

nginx -s <em>signal</em>
로그인 후 복사

여기서 signal은 다음 중 하나일 수 있습니다.

  • stop — 빠른 종료
  • quit — 단계적 종료
  • reload — 구성 파일 다시 로드
  • reopen — 로그 파일 다시 열기

예를 들어 작업자 프로세스가 현재 요청 처리를 완료할 때까지 기다리면서 nginx 프로세스를 중지하려면 다음 명령을 실행할 수 있습니다.

nginx -s quit
로그인 후 복사
이 명령은 동일한 사용자로 실행되어야 합니다. nginx를 시작했습니다.

구성 파일의 변경 사항은 구성을 다시 로드하는 명령이 nginx로 전송되거나 다시 시작될 때까지 적용되지 않습니다. 구성을 다시 로드하려면 다음을 실행합니다.

nginx -s reload
로그인 후 복사
로그인 후 복사

마스터 프로세스가 구성을 다시 로드하라는 신호를 받으면 새 구성 파일의 구문 유효성을 확인하고 제공된 구성을 적용하려고 시도합니다. 그것. 이것이 성공하면 마스터 프로세스는 새로운 작업자 프로세스를 시작하고 이전 작업자 프로세스에 메시지를 보내 종료를 요청합니다. 그렇지 않으면 마스터 프로세스가 변경 사항을 롤백하고 이전 구성으로 계속 작업합니다. 종료 명령을 받은 이전 작업자 프로세스는 새 연결 수락을 중지하고 해당 요청이 모두 처리될 때까지 현재 요청을 계속 처리합니다. 그런 다음 이전 작업자 프로세스가 종료됩니다.

kill 유틸리티와 같은 Unix 도구의 도움을 받아 nginx 프로세스에 신호를 보낼 수도 있습니다. 이 경우 신호는 주어진 프로세스 ID를 가진 프로세스로 직접 전송됩니다. nginx 마스터 프로세스의 프로세스 ID는 기본적으로 다음 위치에 기록됩니다. nginx.pid 또는 /usr/local/nginx/logs 디렉터리의 /var/run입니다. 예를 들어, 마스터 프로세스 ID가 1628인 경우 QUIT 신호를 보내 nginx를 정상적으로 종료하려면 다음을 실행합니다.

kill -s QUIT 1628
로그인 후 복사

실행 중인 모든 nginx 프로세스 목록을 가져오려면 다음을 실행합니다. ps 유틸리티는 예를 들어 다음과 같은 방식으로 사용될 수 있습니다.

ps -ax | grep nginx
로그인 후 복사

nginx로 신호 전송에 대한 자세한 내용은 nginx 제어를 참조하세요.

구성 파일의 구조

nginx는 구성 파일에 지정된 지시어에 의해 제어되는 모듈로 구성됩니다. 지시문은 단순 지시문과 블록 지시문으로 구분됩니다. 단순 지시문은 공백으로 구분된 이름과 매개변수로 구성되며 세미콜론(;). 블록 지시문은 단순 지시문과 구조가 동일하지만 세미콜론 대신 중괄호({ 및})로 묶인 일련의 추가 명령으로 끝납니다. 블록 지시문에 다른 지시문이 있을 수 있는 경우 중괄호 안의 지시문을 컨텍스트라고 합니다(예: 이벤트, http, 서버, 및 위치).

Directives placed in the configuration file outside of any contexts are considered to be in the main context. Theevents and http directives reside in the main context, server in http, and location in server.

The rest of a line after the # sign is considered a comment.

Serving Static Content

An important web server task is serving out files (such as images or static HTML pages). You will implement an example where, depending on the request, files will be served from different local directories: /data/www(which may contain HTML files) and /data/images (containing images). This will require editing of the configuration file and setting up of a server block inside the http block with two location blocks.

First, create the /data/www directory and put an index.html file with any text content into it and create the/data/images directory and place some images in it.

Next, open the configuration file. The default configuration file already includes several examples of the serverblock, mostly commented out. For now comment out all such blocks and start a new server block:

http {
    server {
    }
}
로그인 후 복사

Generally, the configuration file may include several server blocks distinguished by ports on which they listento and by server names. Once nginx decides which server processes a request, it tests the URI specified in the request’s header against the parameters of the location directives defined inside the server block.

Add the following location block to the server block:

location / {
    root /data/www;
}
로그인 후 복사

This location block specifies the “/” prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in the root directive, that is, to /data/www, to form the path to the requested file on the local file system. If there are several matching location blocks nginx selects the one with the longest prefix. The location block above provides the shortest prefix, of length one, and so only if all otherlocation blocks fail to provide a match, this block will be used.

Next, add the second location block:

location /images/ {
    root /data;
}
로그인 후 복사

It will be a match for requests starting with /images/ (location / also matches such requests, but has shorter prefix).

The resulting configuration of the server block should look like this:

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
}
로그인 후 복사

This is already a working configuration of a server that listens on the standard port 80 and is accessible on the local machine at http://localhost/. In response to requests with URIs starting with /images/, the server will send files from the /data/images directory. For example, in response to the http://localhost/images/example.pngrequest nginx will send the /data/images/example.png file. If such file does not exist, nginx will send a response indicating the 404 error. Requests with URIs not starting with /images/ will be mapped onto the /data/wwwdirectory. For example, in response to the http://localhost/some/example.html request nginx will send the/data/www/some/example.html file.

To apply the new configuration, start nginx if it is not yet started or send the reload signal to the nginx’s master process, by executing:

nginx -s reload
로그인 후 복사
로그인 후 복사
In case something does not work as expected, you may try to find out the reason in access.log anderror.log files in the directory /usr/local/nginx/logs or /var/log/nginx.

Setting Up a Simple Proxy Server

One of the frequent uses of nginx is setting it up as a proxy server, which means a server that receives requests, passes them to the proxied servers, retrieves responses from them, and sends them to the clients.

We will configure a basic proxy server, which serves requests of images with files from the local directory and sends all other requests to a proxied server. In this example, both servers will be defined on a single nginx instance.

First, define the proxied server by adding one more server block to the nginx’s configuration file with the following contents:

server {
    listen 8080;
    root /data/up1;

    location / {
    }
}
로그인 후 복사

This will be a simple server that listens on the port 8080 (previously, the listen directive has not been specified since the standard port 80 was used) and maps all requests to the /data/up1 directory on the local file system. Create this directory and put the index.html file into it. Note that the root directive is placed in theserver context. Such root directive is used when the location block selected for serving a request does not include own root directive.

Next, use the server configuration from the previous section and modify it to make it a proxy server configuration. In the first location block, put the proxy_pass directive with the protocol, name and port of the proxied server specified in the parameter (in our case, it is http://localhost:8080):

server {
    location / {
        proxy_pass http://localhost:8080;
    }

    location /images/ {
        root /data;
    }
}
로그인 후 복사

We will modify the second location block, which currently maps requests with the /images/ prefix to the files under the /data/images directory, to make it match the requests of images with typical file extensions. The modified location block looks like this:

location ~ \.(gif|jpg|png)$ {
    root /data/images;
}
로그인 후 복사

The parameter is a regular expression matching all URIs ending with .gif.jpg, or .png. A regular expression should be preceded with ~. The corresponding requests will be mapped to the /data/images directory.

When nginx selects a location block to serve a request it first checks location directives that specify prefixes, remembering location with the longest prefix, and then checks regular expressions. If there is a match with a regular expression, nginx picks this location or, otherwise, it picks the one remembered earlier.

The resulting configuration of a proxy server will look like this:

server {
    location / {
        proxy_pass http://localhost:8080/;
    }

    location ~ \.(gif|jpg|png)$ {
        root /data/images;
    }
}
로그인 후 복사

This server will filter requests ending with .gif.jpg, or .png and map them to the /data/images directory (by adding URI to the root directive’s parameter) and pass all other requests to the proxied server configured above.

To apply new configuration, send the reload signal to nginx as described in the previous sections.

There are many more directives that may be used to further configure a proxy connection.

Setting Up FastCGI Proxying

nginx can be used to route requests to FastCGI servers which run applications built with various frameworks and programming languages such as PHP.

The most basic nginx configuration to work with a FastCGI server includes using the fastcgi_pass directive instead of the proxy_pass directive, and fastcgi_param directives to set parameters passed to a FastCGI server. Suppose the FastCGI server is accessible on localhost:9000. Taking the proxy configuration from the previous section as a basis, replace the proxy_pass directive with the fastcgi_pass directive and change the parameter to localhost:9000. In PHP, the SCRIPT_FILENAME parameter is used for determining the script name, and the QUERY_STRING parameter is used to pass request parameters. The resulting configuration would be:

server {
    location / {
        fastcgi_pass  localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param QUERY_STRING    $query_string;
    }

    location ~ \.(gif|jpg|png)$ {
        root /data/images;
    }
}
로그인 후 복사

This will set up a server that will route all requests except for requests for static images to the proxied server operating on localhost:9000 through the FastCGI protocol.

以上就介绍了Nginx: Beginner’s Guide,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Windows에서 nginx를 구성하는 방법 Windows에서 nginx를 구성하는 방법 Apr 14, 2025 pm 12:57 PM

Windows에서 Nginx를 구성하는 방법은 무엇입니까? nginx를 설치하고 가상 호스트 구성을 만듭니다. 기본 구성 파일을 수정하고 가상 호스트 구성을 포함하십시오. 시작 또는 새로 고침 Nginx. 구성을 테스트하고 웹 사이트를보십시오. SSL을 선택적으로 활성화하고 SSL 인증서를 구성하십시오. 포트 80 및 443 트래픽을 허용하도록 방화벽을 선택적으로 설정하십시오.

Docker 컨테이너의 이름을 확인하는 방법 Docker 컨테이너의 이름을 확인하는 방법 Apr 15, 2025 pm 12:21 PM

단계를 따르면 Docker 컨테이너 이름을 쿼리 할 수 ​​있습니다. 모든 컨테이너 (Docker PS)를 나열하십시오. 컨테이너 목록을 필터링합니다 (GREP 명령 사용). 컨테이너 이름 ( "이름"열에 위치)을 가져옵니다.

Docker가 컨테이너를 시작하는 방법 Docker가 컨테이너를 시작하는 방법 Apr 15, 2025 pm 12:27 PM

Docker Container Startup 단계 : 컨테이너 이미지를 당기기 : "Docker Pull [Mirror Name]"을 실행하십시오. 컨테이너 생성 : "docker"[옵션] [미러 이름] [명령 및 매개 변수]를 사용하십시오. 컨테이너를 시작하십시오 : "Docker start [컨테이너 이름 또는 ID]"를 실행하십시오. 컨테이너 상태 확인 : 컨테이너가 "Docker PS"로 실행 중인지 확인하십시오.

nginx가 시작되었는지 확인하는 방법 nginx가 시작되었는지 확인하는 방법 Apr 14, 2025 pm 01:03 PM

nginx가 시작되었는지 확인하는 방법 : 1. 명령 줄을 사용하십시오 : SystemCTL 상태 nginx (linux/unix), netstat -ano | Findstr 80 (Windows); 2. 포트 80이 열려 있는지 확인하십시오. 3. 시스템 로그에서 nginx 시작 메시지를 확인하십시오. 4. Nagios, Zabbix 및 Icinga와 같은 타사 도구를 사용하십시오.

Docker 용 컨테이너를 만드는 방법 Docker 용 컨테이너를 만드는 방법 Apr 15, 2025 pm 12:18 PM

Docker에서 컨테이너 만들기 : 1. 이미지를 당기기 : Docker Pull [Mirror Name] 2. 컨테이너 만들기 : Docker Run [옵션] [미러 이름] [명령] 3. 컨테이너 시작 : Docker Start [컨테이너 이름]

nginx 버전을 확인하는 방법 nginx 버전을 확인하는 방법 Apr 14, 2025 am 11:57 AM

nginx 버전을 쿼리 할 수있는 메소드는 다음과 같습니다. nginx -v 명령을 사용하십시오. nginx.conf 파일에서 버전 지시문을 봅니다. nginx 오류 페이지를 열고 페이지 제목을 봅니다.

Nginx에서 클라우드 서버 도메인 이름을 구성하는 방법 Nginx에서 클라우드 서버 도메인 이름을 구성하는 방법 Apr 14, 2025 pm 12:18 PM

클라우드 서버에서 nginx 도메인 이름을 구성하는 방법 : 클라우드 서버의 공개 IP 주소를 가리키는 레코드를 만듭니다. Nginx 구성 파일에 가상 호스트 블록을 추가하여 청취 포트, 도메인 이름 및 웹 사이트 루트 디렉토리를 지정합니다. Nginx를 다시 시작하여 변경 사항을 적용하십시오. 도메인 이름 테스트 구성에 액세스하십시오. 기타 참고 : HTTPS를 활성화하려면 SSL 인증서를 설치하고 방화벽에서 포트 80 트래픽을 허용하고 DNS 해상도가 적용되기를 기다립니다.

nginx 서버를 시작하는 방법 nginx 서버를 시작하는 방법 Apr 14, 2025 pm 12:27 PM

Nginx 서버를 시작하려면 다른 운영 체제에 따라 다른 단계가 필요합니다. Linux/Unix System : Nginx 패키지 설치 (예 : APT-Get 또는 Yum 사용). SystemCTL을 사용하여 nginx 서비스를 시작하십시오 (예 : Sudo SystemCtl start nginx). Windows 시스템 : Windows 바이너리 파일을 다운로드하여 설치합니다. nginx.exe 실행 파일을 사용하여 nginx를 시작하십시오 (예 : nginx.exe -c conf \ nginx.conf). 어떤 운영 체제를 사용하든 서버 IP에 액세스 할 수 있습니다.

See all articles