Nginx: 초보자 가이드

WBOY
풀어 주다: 2016-08-08 09:22:19
원래의
880명이 탐색했습니다.

이 가이드에서는 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教程有兴趣的朋友有所帮助。

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!