찾다
백엔드 개발PHP 튜토리얼Nginx: 초보자 가이드

이 가이드에서는 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으로 문의하세요.
unset ()와 session_destroy ()의 차이점은 무엇입니까?unset ()와 session_destroy ()의 차이점은 무엇입니까?May 04, 2025 am 12:19 AM

thedifferencebetweenUnset () andsession_destroy () istssection_destroy () thinatesTheentiresession.1) TEREMOVECIFICESSESSION 'STERSESSIVEBLESSESSIVESTIETSTESTERSALLS'SSOVERSOLLS '를 사용하는 것들

로드 밸런싱의 맥락에서 스티커 세션 (세션 친화력)이란 무엇입니까?로드 밸런싱의 맥락에서 스티커 세션 (세션 친화력)이란 무엇입니까?May 04, 2025 am 12:16 AM

stickysessionsureSureSureRequestSaroutEdToTheSERSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESINCENSENCY

PHP에서 사용할 수있는 다른 세션 저장 핸들러는 무엇입니까?PHP에서 사용할 수있는 다른 세션 저장 핸들러는 무엇입니까?May 04, 2025 am 12:14 AM

phpoffersvarioussessionsaveAndlers : 1) 파일 : 기본, 단순, 단순한 BUTMAYBOTTLENECKONHIGH-TRAFFICSITES.2) MEMCACHED : 고성능, IdealForspeed-CriticalApplications.3) Redis : SimilartomemCached, WithaddedPersistence.4) 데이터베일 : OffforIntegrati

PHP의 세션은 무엇이며 왜 사용됩니까?PHP의 세션은 무엇이며 왜 사용됩니까?May 04, 2025 am 12:12 AM

PHP의 세션은 여러 요청간에 상태를 유지하기 위해 서버 측의 사용자 데이터를 저장하는 메커니즘입니다. 구체적으로, 1) 세션은 session_start () 함수에 의해 시작되며 데이터는 $ _session Super Global Array를 통해 저장되어 읽습니다. 2) 세션 데이터는 기본적으로 서버의 임시 파일에 저장되지만 데이터베이스 또는 메모리 스토리지를 통해 최적화 할 수 있습니다. 3) 세션은 사용자 로그인 상태 추적 및 쇼핑 카트 관리 기능을 실현하는 데 사용될 수 있습니다. 4) 세션의 보안 전송 및 성능 최적화에주의를 기울여 애플리케이션의 보안 및 효율성을 보장하십시오.

PHP 세션의 수명주기를 설명하십시오.PHP 세션의 수명주기를 설명하십시오.May 04, 2025 am 12:04 AM

phpsessionsStartWithSession_start (), whithesauniqueIdAndCreatesErverFile; thepersistacrossRequestSandCanBemanBledentSandwithSession_destroy ()

절대 세션 타임 아웃의 차이점은 무엇입니까?절대 세션 타임 아웃의 차이점은 무엇입니까?May 03, 2025 am 12:21 AM

절대 세션 시간 초과는 세션 생성시 시작되며, 유휴 세션 시간 초과는 사용자가 작동하지 않아 시작합니다. 절대 세션 타임 아웃은 금융 응용 프로그램과 같은 세션 수명주기의 엄격한 제어가 필요한 시나리오에 적합합니다. 유휴 세션 타임 아웃은 사용자가 소셜 미디어와 같이 오랫동안 세션을 활성화하려는 응용 프로그램에 적합합니다.

세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?May 03, 2025 am 12:19 AM

서버 세션 고장은 다음 단계를 따라 해결할 수 있습니다. 1. 서버 구성을 확인하여 세션이 올바르게 설정되었는지 확인하십시오. 2. 클라이언트 쿠키를 확인하고 브라우저가 지원하는지 확인하고 올바르게 보내십시오. 3. Redis와 같은 세션 스토리지 서비스가 정상적으로 작동하는지 확인하십시오. 4. 올바른 세션 로직을 보장하기 위해 응용 프로그램 코드를 검토하십시오. 이러한 단계를 통해 대화 문제를 효과적으로 진단하고 수리 할 수 ​​있으며 사용자 경험을 향상시킬 수 있습니다.

session_start () 함수의 중요성은 무엇입니까?session_start () 함수의 중요성은 무엇입니까?May 03, 2025 am 12:18 AM

session_start () iscrucialinphpformanagingUsersessions.1) itiniteSanewsessionifnoneexists, 2) ResumesAnxistessions, and3) setSasessionCookieForContInuityAcrosrequests, enablingplicationsirecationSerauthenticationAndpersonalizestContent.

See all articles

핫 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

메모장++7.3.1

메모장++7.3.1

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

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.