Linux/Linux 실습

Linux 서버에 Nginx 설치 연동

GGkeeper 2022. 1. 5. 01:07

미션1> 아래 조건에 맞게 서버를 구성하시오.

구성 핵심 : CentOS Linux 7을 설치하고 Nginx를 이용한 서비스를 구성한다.

-- 조건 --
1. Linux 배포판 : CentOS Linux 7 (레드햇 계열)
- 다운로드 : http://ftp.daum.net/
- CentOS Linux 버전 : CentOS-7-x86_64-Minimal-2009.iso
2. 네트워크 : 
- IP 주소 : 192.168.108.112/24
- GateWay : 192.168.108.2
- DNS : 168.126.63.1
3. 서비스 : Nginx + Php + MariaDB 구성
4. 방화벽 : X
-- 조건 --

1. CentOS 7 설치
CentOS 7을 다운로드 받아서 설치한다.

2. NginX 설치

Nginx(엔진x)  
참고 : https://ko.wikipedia.org/wiki/Nginx
Nginx는 아파치 웹서버와 다음으로 많이 사용하는 웹서버이며 동작이 단순하며 
Nginx의 목표인 가벼움과 높은 성능으로 동시접속 처리에 특화된 웹서버이다.

개발자 : Igor Sysoev (러시아 개발자)
발표일 : 2004년 10월 4일
프로그래밍 언어 : C
운영 체제 : 크로스 플랫폼
종류 : 웹서버, 프록시 서버/리버스 프록시
라이선스 : BSD 허가서(2조항)
웹사이트 : http://www.nginx.org/

참고로 네이버가 Nginx를 사용하는 대표적인 사이트이다.

https://d2.naver.com/helloworld/192785

Nginx를 설치하기 위해서 저장소를 생성한다.
저장소 위치 : /etc/yum.repos.d/nginx.repo
# vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

php-fpm 통신 방법 : 소켓파일
php를 사용하기 위해서는 php-fpm을 설치한다.
php-fpm은 PHP FastCGI Process Manager의 약자로 FastCGI는 CGI보다 더 빠른 처리를 말한다.

# yum -y install nginx php php-mysql php-fpm mariadb mariadb-server

GD 라이브러리를 설치한다.
# yum -y install php-gd gd gd-devel libjpeg libjpeg-devel giflib giflib-devel libpng libpng-devel freetype freetype-devel

서버를 자동으로 구동시키기 위해서 서비스를 활성화한다.
# systemctl enable php-fpm
# systemctl enable nginx
# systemctl enable mariadb

3. MariaDB 설정
MariaDB 설정파일을 utf8로 동작할 수 있도록 수정한다.
# vi /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
collation-server = utf8_general_ci
character-set-server = utf8
skip-character-set-client-handshake
bind-address = 127.0.0.1
  :
  :(생략)

MariaDB를 시작한다.
# systemctl start mariadb
# ss -nlt | grep 3306
LISTEN     0      50     127.0.0.1:3306                     *:*   

관리자 비빌번호를 설정한다.
mysqladmin 명령어를 이용해서 관리자(root) 비밀번호를 설정한다.
# mysqladmin -h localhost -u root -p password
Enter password:        <-- 엔터 (현재 비번)
New password:          <-- P@ssw0rd 입력 (새로운 비번)
Confirm new password:  <-- P@ssw0rd 입력 (새로운 비번 확인)

비밀번호 설정이 완료되면 root 권한으로 DBMS에 접속한다.
# mysql -h localhost -u root -p
Enter password:    <-- P@ssw0rd 입력
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

MariaDB [(none)]> quit

# vi .my.cnf
[client]
host = localhost
user = root
password = P@ssw0rd

4. php 설정
php 설정 파일 : /etc/php.ini
/etc/php.ini 파일을 열어서 아래 내용의 설정을 변경한다.
# vi /etc/php.ini
date.timezone = Asia/Seoul
short_open_tag = On
expose_php = Off
display_errors = On

php-fpm 의 지시어를 소켓파일로 수정한다.
# vi  /etc/php-fpm.d/www.conf
;listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php-fpm.sock

; .html 확장자를 php로 인식하게 설정한다.
security.limit_extensions = .php .html

php-fpm 서비스를 시작한다.
# systemctl start php-fpm
# ls /var/run/php-fpm/ -l
합계 4
-rw-r--r--. 1 root root 4  7월 30 10:19 php-fpm.pid
srw-rw-rw-. 1 root root 0  7월 30 10:19 php-fpm.sock

# cat /var/run/php-fpm/php-fpm.pid
# ps aux | grep fpm

5. nginx 설정
/etc/nginx/  :  nginx 관련 파일들이 저장된 디렉터리
|-- conf.d   :  nginx 설정 파일들이 저장된 디렉터리
|   `-- default.conf
|-- fastcgi_params
|-- koi-utf
|-- koi-win
|-- mime.types
|-- modules -> ../../usr/lib64/nginx/modules
|-- nginx.conf  : nginx 메인 설정 파일 
|-- scgi_params
|-- uwsgi_params
`-- win-utf


# vi /etc/nginx/conf.d/default.conf
server {
    listen       80;
    server_name  localhost;

    # 문자셋 설정
    charset utf-8;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        # WEB root 디렉터리 변경
        # root   /usr/share/nginx/html;
        root   /var/www/html;
        index  index.html index.php;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        #root   /usr/share/nginx/html;
        root  /var/www/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    # .php .html 확장자를 php로 인식하게 설정한다.
    location ~ \.(php|html)$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
         fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
         fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
         fastcgi_param  SCRIPT_FILENAME  /var/www/html$fastcgi_script_name;
         include        fastcgi_params;
    }


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

nginx를 시작한다.
# systemctl start nginx

80번 포트를 확인한다.
# ss -nltp
# yum -y install net-tools
# netstat -nltp

웹페이지를 생성한다.
# cd /var/www/html
# vi index.html
<?
phpinfo();
?>

firewalld 방화벽을 중지한다.
# systemctl stop firewalld
# systemctl disable firewalld

iptables-services 패키지를 설치한다.
# yum -y install iptables-services
# systemctl enable iptables

iptables 방화벽 룰을 설정한다.
iptables -F
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -j DROP
iptables-save > /etc/sysconfig/iptables

서버의 IP주소로 접속해서 phpinfo 페이지가 잘 나오는지 확인한다.
http://192.168.108.112/

6. DB 연동하기
PHP에서 DB에 테이블을 하나 생성해서 로그인/로그아웃 기능을 구현한다.
DB 사용자 : nginxuser
DB 비밀번호 : P@ssw0rd
DB명 : nginxuser
TB명 : member
member TB's 스토리지 엔진 : MyISAM
member TB's 구조 : 
no       : 컬럼1 int형, 널허용 금지, 자동증가, 기본키 지정
userid   : 컬럼2 가변길이 문자형이며 크기는 20자 까지, 널 허용 금지, 유일한 값 지정
userpw   : 컬럼3 고정길이 문자형이며 크기는 41자 까지, 널 허용 금지 
username : 컬럼4 가변길이 문자형이며 크기는 20자 까지, 널 허용 금지 
regdate  : 컬럼5 datetime형
스토리지 엔진 : MyISAM 
언어셋     : utf8

not null : 널 허용 금지
auto_increment : 자동 증가
primary key : 기본 키
unique : 유일한 값
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| no       | int(11)     | NO   | PRI | NULL    | auto_increment |
| userid   | varchar(20) | NO   | UNI | NULL    |                |
| userpw   | char(41)    | NO   |     | NULL    |                |
| username | varchar(20) | NO   |     | NULL    |                |
| regdate  | datetime    | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

# cd
# vi .my.cnf
[client]
host = localhost
user = root
password = P@ssw0rd

# mysql mysql
select user();
delete from user where password = '';
delete from db;
create database nginxuser;
show databases;
grant all privileges on nginxuser.* to nginxuser@localhost identified by 'P@ssw0rd';

MariaDB [mysql]> select host,user,password from user;
+-----------+-----------+-------------------------------------------+
| host      | user      | password                                  |
+-----------+-----------+-------------------------------------------+
| localhost | root      | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| localhost | nginxuser | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
+-----------+-----------+-------------------------------------------+
2 rows in set (0.00 sec)


MariaDB [mysql]> select host,user,db from db;
+-----------+-----------+-----------+
| host      | user      | db        |
+-----------+-----------+-----------+
| localhost | nginxuser | nginxuser |
+-----------+-----------+-----------+
1 row in set (0.00 sec)

MariaDB [mysql]> quit


DB 사용자 테스트
# mysql -u nginxuser -p nginxuser
Enter password:  <-- P@ssw0rd 입력

create table a(id int);
show tables;
insert into a values(1);
select * from a;
delete from a;
select * from a;
drop table a;
show tables;

member 테이블 생성
create table member
(
    no       int not null primary key auto_increment comment '회원번호', 
    userid   varchar(20) not null unique comment '회원아이디', 
    userpw   char(41) not null comment '회원비밀번호',
    username varchar(20) not null comment '회원이름',
    regdate  datetime not null comment '가입날짜'
)Engine=MyISAM default charset=utf8;

MariaDB [nginxuser]> show tables;
+---------------------+
| Tables_in_nginxuser |
+---------------------+
| member              |
+---------------------+
1 row in set (0.00 sec)

MariaDB [nginxuser]> desc member;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| no       | int(11)     | NO   | PRI | NULL    | auto_increment |
| userid   | varchar(20) | NO   | UNI | NULL    |                |
| userpw   | char(41)    | NO   |     | NULL    |                |
| username | varchar(20) | NO   |     | NULL    |                |
| regdate  | datetime    | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

insert into member values(NULL, 'test', password('P@ssw0rd'), '홍길동', now());
insert into member values(NULL, 'test2', password('111111'), '고길동', now());

MariaDB [nginxuser]> select * from member;
+----+--------+-------------------------------------------+-----------+---------------------+
| no | userid | userpw                                    | username  | regdate             |
+----+--------+-------------------------------------------+-----------+---------------------+
|  1 | test   | *8232A1298A49F710DBEE0B330C42EEC825D4190A | 홍길동    | 2021-07-30 11:35:46 |
|  2 | test2  | *FD571203974BA9AFE270FE62151AE967ECA5E0AA | 고길동    | 2021-07-30 11:36:17 |
+----+--------+-------------------------------------------+-----------+---------------------+
2 rows in set (0.00 sec)
MariaDB [nginxuser]> quit


7. 로그인 페이지 생성
login.html loginok.html logout.html 파일을 생성한다.

login.html    : 로그인 페이지
loginok.html  : 로그인 인증 페이지 (DB 연동 부분)
logout.html   : 로그아웃 페이지

               로그아웃 흐름도
   +--------------------------------------+
   |                                      |
   |                                      |
   |                                      v
로그인 페이지     로그인 인증        로그아웃 페이지
login.html -----> loginok.html ----> logout.html 
       로그인 흐름도      |           (세션 삭제)
   ^                   |                  |
   |                   |                  |
   +-------------------+                  |
   (DB 확인 + 세션 생성)                     |
   ^                                      |
   |                                      |
   +--------------------------------------+


# cd /var/www/html

:set noai :set paste 를 설정하고 붙여넣기를 한다.
# vi login.html
<?
session_start();
/*
 * 파일명 : loginok.html
 * 프로그램 설명 : 로그인 프로그램
 * 작성자 : http://linuxmaster.net/
 */
?>

<html>
<head>
  <title> ::: 로그인 프로그램 ::: </title>
  <meta charset="utf-8"/>
</head>

<body>

<?
if(isset($_SESSION['userid']))  // 로그인 했다면
{
?>

<table align=center border=1 cellpadding=5 cellspacing=0>
<tr align=center>
  <td align=center> <?=$_SESSION['username'] ?> 님 환영합니다. </td>
</tr>
<tr align=center>
  <td align=center> <a href=logout.html> 로그아웃 </a> </td>
</tr>
</table>

<?
} else {  // 로그아웃 했다면 
?>
<form method=post action=loginok.html>
<table align=center border=1 cellpadding=5 cellspacing=0>
<tr align=center>
  <td> 아이디 </td> <td> <input type=text name=userid> </td>
<tr>
<tr align=center>
  <td> 비밀번호 </td> <td> <input type=password name=userpw> </td>
<tr>
<tr align=center>
  <td align=center colspan=2> <input type=submit value=로그인> </td>
<tr>
</table>
</form>

<?
}
?>

</body>
</html>

# vi loginok.html
<?
session_start();  // 세션 시작

/*
 * 파일명 : loginok.html
 * 프로그램 설명 : DB에 사용자/비밀번호를 확인하고 세션을 생성하는 프로그램
 * 작성자 : http://linuxmaster.net/
 */

// 디버깅 시 사용
//print_r($_POST);
//exit;

// DB를 root로 접속하면 보안상 문제가 발생되므로 일반 유저로 접속해야 한다.
$DBHOST="localhost";
$DBUSER="nginxuser";
$DBPASS="P@ssw0rd";
$DBNAME = "nginxuser";
$TBNAME = "member";

# DBMS 접속
#resource mysql_connect(서버명,사용자,비번)
$connect = mysqli_connect($DBHOST, $DBUSER, $DBPASS, $DBNAME) or die("DBMS에 접속 실패");

# DB 선택
# mysql_select_db(DB명, 연결정보)
//mysqli_select_db($DBNAME);

# 쿼리 실행
$query = "SELECT * FROM $TBNAME WHERE userid = '$_POST[userid]' and userpw = password('$_POST[userpw]') ";

/* 디버깅 용도
 * echo $query;
 * exit;
 */

# resource mysql_query(쿼리문, 연결정보)
# resource mysqli_query(연결정보, 쿼리문)
$result = mysqli_query($connect, $query);

# 전체 자료 수가 1이면 userid / userpw 가 일치했다는 의미이다.
$num = mysqli_num_rows($result);

if($num)
{  // 세션 생성
    $row = mysqli_fetch_array($result); // $row 변수에 연관 배열로 저장한다.
    // echo "디버깅 : $num <br>";
    // echo "디버깅 : $row[username]";
    // exit;
    $_SESSION['userid'] = $row['userid'];  // 세션변수 userid 를 생성한다.
    $_SESSION['username'] = $row['username']; // 세션변수 username 을 생성한다.
   echo " <script language=JavaScript>
          <!--
              location.href = 'login.html';
          //-->
          </script>
        ";

} else { // userid / userpw 가 틀렸다면 에러메세지를 출력하고 이제 페이지로 돌려보낸다.
   echo " <script language=JavaScript>
          <!--
              alert('아이디/비번을 확인해주세요.');
              history.go(-1);
          //-->
          </script>
        ";
}

?>

# vi logout.html
<?
/*
 * 파일명 : logout.html
 * 프로그램 설명 : 로그아웃 프로그램
 * 작성자 : http://linuxmaster.net/
 */
session_start();    // 세션 시작
session_destroy();  // 세션 삭제



// login.html 로 다시 돌려 보낸다.
echo " <script language=JavaScript>
       <!--
          location.href = 'login.html';
       //-->
       </script>
     ";
?>

8. 웹페이지 접속
로그인 페이지에 접속해서 로그인이 잘 되는지 확인한다.
로그인이 된다면 : DB연동이 잘되는 것이다.
로그인이 안된다면 : DB연동에 문제가 있는 것이다.
http://192.168.108.112/login.html