분류 php

Apache2에서 Nginx 웹 서버로 이동

컨텐츠 정보

  • 조회 532 (작성일 )

본문

최근에는 개발, 스테이징 및 프로덕션 웹 서버를 Apache2에서 Nginx로 옮겨야 했습니다. 이러한 이동의 이유는 회사의 나머지 부분에서는 모든 백엔드 서비스에 Nginx를 사용하지만 웹 사이트가 어떤 이유로 든 컨설턴트가 Apache2를 설정했기 때문입니다. 

이것은 주로 관리에 문제가 되었습니다. 이 기사에서는 프로세스를 단계별로 진행합니다. 

모든 스크린 샷에 빈 상자를 사용하지만 실제 서버에서 수행 한 단계는 동일합니다.


https://dev.to/davinderpalrehal/moving-from-apache2-to-nginx-webserver-2n6a 


Server 


내 테스트 서버의 경우 vagrant 및 ubuntu / bionic64를 사용하고 있습니다. 이 서버에는 기본 LAMP 스택인 apache2.4, php7.2 및 mysql5.7이 있습니다. Apache를 Nginx로 대체하는 LEMP 스택으로 옮길 것입니다.


이 서버에는 WordPress 5.2.4가 실행 중인 WordPress 사이트가 있습니다. Nginx 및 PHP 7.3에서 실행되는 이 WordPress 사이트를 볼 수 있다면 목표를 달성했을 것입니다. 아 그리고 우리는 Nginx 설치로 전송 해야 하는 Apache2 인스턴스의 많은 envvar를 설정했습니다.


Nginx 설치 


꽤 직설적 인. 업데이트를 확인하여 시작하십시오.


sudo apt update
sudo apt upgrade

실제로 Nginx를 설치하십시오.


sudo apt install nginx

Nginx가 설치되었지만 실행 중이 아닙니다. Apache2가 이미 시스템에 설치 및 구성되어 있기 때문에 Apache2는 포트 80을 사용하므로 충돌을 피하기 위해 모든 포트가 제대로 작동하는지 테스트 하기 위해 다른 포트에서 Nginx를 실행해야 합니다. 포트 8080을 선택합니다.


포트 8080으로 Nginx 구성 


Nginx (아파치와 마찬가지로)로 작동하는 기본 웹 사이트가 있습니다. 구성을 볼 수 있습니다.


sudo vim /etc/nginx/sites-available/default

다음과 같은 파일이 열립니다.


##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
  listen 80 default_server;
  listen [::]:80 default_server;
  
  # SSL configuration
  #
  # listen 443 ssl default_server;
  # listen [::]:443 ssl default_server;
  #
  # Note: You should disable gzip for SSL traffic.
  # See: https://bugs.debian.org/773332
  #
  # Read up on ssl_ciphers to ensure a secure configuration.
  # See: https://bugs.debian.org/765782
  #
  # Self signed certs generated by the ssl-cert package
  # Don't use them in a production server!
  #
  # include snippets/snakeoil.conf;
  
  root /var/www/html;

  # Add index.php to the list if you are using PHP
  index index.html index.htm index.nginx-debian.html;

  server_name _;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
  }
  # pass PHP scripts to FastCGI server
  #
  #location ~ \.php$ {
  #  include snippets/fastcgi-php.conf;
  #
  # # With php-fpm (or other unix sockets):
  #  fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
  # # With php-cgi (or other tcp sockets):
  #  fastcgi_pass 127.0.0.1:9000;
  #}

  # deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
  #
  #location ~ /\.ht {
  #       deny all;
  #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#  listen 80;
#  listen [::]:80;
#
#  server_name example.com;
#
#  root /var/www/example.com;
#  index index.html;
#
#  location / {
#    try_files $uri $uri/ =404;
#  }
#}

22 번과 23 번 줄에서 80에서 8080으로 바꿀 것입니다.


listen 8080 default_server;
listen [::]:8080 default_server;


Nginx 서비스를 시작하기 전에 설정을 빠르게 테스트 해 봅시다.


sudo nginx -t


모든 것이 잘되면 서버가 작동 중임을 알려주는 작은 HTML 페이지를 작성하십시오. 41 번 줄은 서버의 루트를 보여줍니다. Apache와 동일한 디렉토리를 사용하지 않도록 서버 루트를 변경했습니다.


root /srv/www/html;


이것이 index.html 파일을 추가 할 디렉토리입니다. 이제 서버를 시작할 수 있습니다.


sudo service nginx start

새 구성을 테스트합니다.


curl http://localhost:8080


내가 만든 새 HTML 파일을 반환해야 합니다. 계속해서 PHP를 설치하십시오.


PHP 설치 


전체 PHP7.2와 Nginx 설정에 약간의 두려움이 있었으므로 PHP7.2로 시스템에 PHP7.2를 설치했습니다.


우선 우분투는 PHP7.3을 어디서 구할 수 있는지 모르기 때문에 리포지토리를 추가해야 합니다.


sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt upgrade


실제로 PHP7.3 및 일부 확장 설치. 이것들은 내가 필요로 하는 확장 프로그램이므로 필요에 따라 확장 프로그램을 자유롭게 추가하거나 제거하십시오.


sudo apt install php7.3
sudo apt install php7.3-cli php7.3-fpm php7.3-pdo php7.3-mysql php7.3-zip  php7.3-mbstring php7.3-curl php7.3-xml php7.3-bcmath php7.3-json


모든 확장이 설치되면 Nginx 설정 파일을 다시 편집하여 우리가 가지고 있는 웹 사이트가 PHP를 사용한다는 것을 알려야 합니다. 구성 파일은 아래에 있으며 모든 주석이 제거되고 변경된 행에서만 주석이 표시됩니다.


server {
  # Using port 8080 only for testing purposes
  listen 8080 default_server;
  listen [::]:8080 default_server;
  
  # Where are the files that are being served
  root /srv/www/html;

  # Default Index file being served, have added `index.php`
  index index.php index.html index.htm index.nginx-debian.html;

  server_name _;

  location / {
    # Added support for PHP routers
    try_files $uri $uri/ /index.php?args =404;
  }

  # Adding support for PHP7.3
  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    # Adding environmental variables for this website
    include /srv/config/default.nginx.conf;
  }
}

구문 오류가 없는지 구성을 테스트하십시오.


sudo nginx -t


/srv/config/default.nginx.conf에 env 파일이 없기 때문에 오류가 발생했을 수 있습니다. 지금 빈 파일을 추가하면 나중에 무엇을 하는지 설명 할 것입니다.


희망적으로, 그것은 당신의 오류를 해결했습니다. 이제 index.html 파일을 index.php로 변경하고 기본 PHP 코드를 추가하여 작동하는지 확인하십시오. 또한 index.php 파일에 대한 적절한 권한을 설정하십시오. 나는 가고 싶어요.


sudo chmod 755 index.php

Nginx 서버를 다시 시작하십시오


sudo service nginx restart


그리고 당신은 당신이 작성한 PHP 파일을 볼 수 있습니다. 구성이 올바른지 확인하기 위해 phpinfo() 함수를 인쇄했습니다.


서버 환경 변수 


내 앱 구성 중 일부를 $_SERVER superglobal에 저장하는 것이 좋습니다. 개발자, 스테이지 및 제품 서버 간에 앱을 이동하고 DB 비밀번호 또는 API 엔드 포인트를 계속 변경하지 않으려는 경우에 유용합니다.


우리가 /srv/config/default.nginx.conf를 건드린 파일에는 다음 코드 줄을 추가 할 것입니다.


fastcgi_param   APP_ENV         dev;
fastcgi_param   APP_ENDPOINT    https://dev.server.com;
fastcgi_param   DB_HOST         localhost;
fastcgi_param   DB_USER         root;
fastcgi_param   DB_PASS         password;


형식은 보통


fastcgi_param  {VAR_NAME}      {VAR_VALUE};


다른 환경 변수를 자유롭게 추가하십시오. 테스트 설정이 끝나면 Nginx를 다시 시작하십시오. 아래와 같이 phpinfo() 함수 출력에 새 변수가 표시 되어야 합니다.

PHP Server variables 


마지막 5 개 값에 주의를 기울이십시오.


그리고 모든 파일을 관련 폴더로 옮기면 최종 테스트를 수행 할 수 있습니다. 준비되면 Apache 서비스를 중지 할 수 있습니다.


sudo service apache2 stop


Nginx 설정에서 포트 번호를 8080에서 80으로 변경하고 Nginx를 다시 시작하면 완료됩니다.