본문 바로가기
개발일기/aws, cafe24

cenos7(cafe24가상호스팅)에 nginx + php7 + mariadb설치

by 프로그래머콩 2019. 2. 4.

0) 개요

OS 
CentOS Linux release 7.3.1611 (Core)
nginx/php
nginx version: nginx/1.10.2 / PHP 7.0.18
mysql Ver
mysql  Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
경로

  • home폴더 - /home/admin/www/
  • nginx기본설정 - vi /etc/nginx/conf.d/wordpress.conf
  • php.ini설정 - php기본 환경 설정 - vi /etc/php.ini
  • www.conf설정 - ning와 php연결 작업 - vi /etc/php-fpm.d/www.conf
  • mysql 언어셋 설정 - vi /etc/my.cnf
  • phpMyAdmin설정 - /home/admin/www/phpMyAdmin/config.inc.php

1) 리눅스 버전체크

 [root@solrafire etc]# uname -a 
 [root@solrafire etc]# Linux lael-centos 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19  22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

2) CentOS 버전체크

[root@solrafire etc]# cat /etc/redhat-release
[root@solrafire etc]# CentOS Linux release 7.3.1611 (Core)


3) 하드용량체크(25g 용량 있고, 3g기본 사용중)

[root@solrafire etc]# df -h


[root@solrafire etc]#
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root   25G  3.0G   21G  13% /
devtmpfs                 486M     0  486M   0% /dev
tmpfs                    496M     0  496M   0% /dev/shm
tmpfs                    496M  6.6M  490M   2% /run
tmpfs                    496M     0  496M   0% /sys/fs/cgroup
/dev/vda1                477M  166M  282M  38% /boot
tmpfs                    100M     0  100M   0% /run/user/0



4-1) CPU 코어수 확인(8)

  
  [root@solrafire etc]# cat /proc/cpuinfo | grep processor | wc -l
  8

5) 자잘한 업글

패키지 목록 갱신 및 업데이트 체크.
#yum update

6) 시스템 시간 설정(이걸 하지 않으면 EST 시간을 불러옴.)

#ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime


7-1) [선택사항][안했음]느린 yum public mirror를 제외(exclude)시키기
- centos의 업데이트 서버 한국 미러서버에 mirror.khlug.org, data.icehosting.co.kr가 있는데, 속도 제한(QoS)가 설정 되어 있는지 1kb/sec의 속도가 나올정도로 상당히 느리다. 이로 인해 업데이트 자업이 엄청나게 오래 걸리게 되므로, 위 서버들은 예외 되도록 설정한다. 


[root@solrafire etc]#  cat /etc/yum/pluginconf.d/fastestmirror.conf
[main]
enabled=1
verbose=0
always_print_best_host = true
socket_timeout=3
#  Relative paths are relative to the cachedir (and so works for users as well
# as root).

hostfilepath=timedhosts.txt
maxhostfileage=10
maxthreads=15

#exclude=.gov, facebook
#include_only=.nl,.de,.uk,.ie

exclude=nicehosting



7-2) 만약 yum update나 yum check-update를 실행했는데 “loaded logins: fastestmirror” 라는 메시지가 나오고 hang on 된다면(1) 

Red Hat Customer 포털 사이트에 기재된 내용. 

  
  1. Make sure the ROM database is functional.
cp -arv /var/lib/rpm /var/lib/rpm.bak
rm -f /var/lib/rpm/__db*
/usr/lib/rpm/rpmdb_verify /var/lib/rpm/Packages

  1. Remove the external repos and test again
mkdir /etc/yum.repos.d/old
mv /etc/yum.repos.d/*repo /etc/yum.repos.d/old
rm -rf /var/cache/yum/*
yum repolist -v

  1. yum restart.



8) [선택사항][안했음]시스템 전체에 대한 Global한 기본 게이트웨이 주소설정과 호스트네임, 네트워킹 연결 허용 여부를 설정한다.
  
$ vi /etc/sysconfig/network

NETWORKING=yes
HATEWAY=192.168.0.1

#재시작
$ /etc/rc.d/init.d/network restart

9) nginx 설치
  
$ yum install nginx

# openssl
$ yum install -y openssl openssl-devel

# 시스템 부팅 될 때 자동으로 실행

$ systemctl start nginx.service

$ systemctl enable nginx.service

9) php설치
  
# 최신 repo 업데이트 받은 후, 


 
# 설치진행

$ yum install -y php70w
$ yum install -y php70w-common php70w-devel php70w-mysql php70w-xml php70w-soap
$ yum install -y php70w-xmlrpc php70w-pear php70w-mbstring php70w-json php70w-gd php70w-mcrypt

$ yum install -y php70w-opcache


# PHP-FPM 설치

$ yum install -y php70w-fpm



10) php.ini 설정
php.ini설정 - php기본 환경 설정

$ vi /etc/php.ini

#nginx 보안을 위해

cgi.fix_pathinfo = 0            

allow_url_fopen = Off

expose_php = Off

display_errors = Off

upload_max_filesize = 1000M

date.timezone = Asia/Seoul

...

memory_limit = 4000M

post_max_size = 200M

...

max_input_vars = 2000


# 재시작

$ service php-fpm restart # centos7에서는 systemctl restart php-fpm.service 변경

$ service nginx restart # centos7에서는 systemctl restart nginx.service 변경




www.conf설정 - ning와 php연결 작업

$ vi /etc/php-fpm.d/www.conf

user = nginx

group = nginx

listen.owner = nginx

listen.group = nginx

listen.mode = 0664

listen = /var/run/php70w-fpm.sock

#시작

$ systemctl start php-fpm     

#부팅시 자동 실행 설정

$ systemctl enable php-fpm  

#상태 확인

$ systemctl status php-fpm    


11) nginx conf설정(/etc/nginx)
 

사용자 추가 및 권한 설정

 #user폴더 권한주기

# nginx를 사용하며, 사용자는 press이고 그룹은 nginx

$useradd admin –g nginx

# 패스워드 변경

$passwd admin

# 권한 변경

$chmod 775 admin

# admin 폴더에서 www 폴더를 생성하고 775로 변경


홈디렉토리를 사용자 계정으로 변경할 때, 웹접근 권한 추가

# 웹에서 access denied가 나타날 경우 아래와 같이 입력

$chcon -Rt httpd_sys_content_t /home/admin


/etc/nginx/conf.d/wordpress.conf설정

server {

   client_body_buffer_size 8k;

   client_header_buffer_size 1k;

   client_max_body_size 40M;

   large_client_header_buffers 8 64k;

   client_body_timeout 10;

   client_header_timeout 10;

   keepalive_timeout 15;

   send_timeout 10;


   listen 80;

   # listen [::]:80 default_server ipv6only=on;


   root /home/admin/www;

   index index.php index.html index.htm;


   # Make site accessible from http://localhost/

   server_name (본인 서버네임 입력)


   location / {

       index index.php

       try_files $uri $uri/ /index.php?args;

   }

    location /phpmyadmin {

        index index.php
        try_files $uri $uri/ /index.php?args;

    }

   # Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests

   #location /RequestDenied {

   #       proxy_pass http://127.0.0.1:8080;

   #}

   location = /favicon.ico {

       log_not_found off;

       access_log off;

   }


   location = /robots.txt {

       allow all;

       log_not_found off;

       access_log off;

   }


   # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).

   # Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)

   location ~ /\. {

       deny all;

   }


   if (!-e $request_filename) {


       rewrite /wp-admin$ $scheme://$host$uri/ permanent;

       #rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;

       #rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;

       rewrite ^(?!^/home/press/www)(/[^/]+)?(/wp-.*) $2 last;

       rewrite ^(?!^/home/press/www)(/[^/]+)?(/.*\.php) $2 last;


       # permalink for postname

       rewrite ^(.*)$ /index.php?q=$1 last;

   }


   # Directives to send expires headers and turn off 404 error logging.

   location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {

       access_log off; log_not_found off; expires max;

   }


   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 /home/press/www;

   }



   # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

   location ~ \.php$ {

       fastcgi_split_path_info ^(.+\.php)(/.+)$;


       # With php5-fpm:

       fastcgi_pass unix:/var/run/php70w-fpm.sock;

       fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;

       fastcgi_param SCRIPT_NAME $fastcgi_script_name;

       fastcgi_index index.php;

       include fastcgi_params;

       # include fastcgi.conf;


       # 502

       proxy_buffer_size               128k;

       proxy_buffers                   4 256k;

       proxy_busy_buffers_size         256k;


       # 502

       fastcgi_buffer_size             16k;

       fastcgi_buffers                 16 16k;


       # timeout

       fastcgi_connect_timeout         600s;

       fastcgi_send_timeout            600s;

       fastcgi_read_timeout            600s;


       #

       sendfile                        on;

       tcp_nopush                      off;

       keepalive_requests              0;

   }


   # deny access to .htaccess files, if Apache's document root

   # concurs with nginx's one

   location ~ /\.ht {

       deny all;

   }

}



12)mariadb설치 및 php-db연동


$yum install mariadb
$yum install mariadb-server
$systemctl start mariadb
$systemctl enable mariadb $systemctl status mariadb mariaDB 환경설정
$ /usr/bin/mysql_secure_installation 기본언어셋
$ vi /etc/my.cnf [mysqld]

항목에 다음 2줄을 추가한다.

character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci



13)mysql(mariadb)외부 ip접근 차단/차단해제 설정.

#mysql 접속 후 접속하고자 하는 계정에 ip접근에 관한 설정정보 추가

$INSERT INTO mysql.user(host,user,password) VALUES(%,’root’,password(‘패스워드’));
# % = 모든 ip접속허용,
# 192.168.% = 특정 망 허용


# 추가한 사용자 환경에서 모든 DB와 테이블에 접근할 수 있는 권한 설정
GRANT ALL PRIVILEGES ON *.* TO ‘root’@‘%’;

#mysql(mariadb) 빠져나오기
$exit

#설정 파일 확인 및 차단 설정관련 구문 삭제
$ vi /etc/my.cnf

# 아래의 구문은 보안을 위해 DB에 직접 연결할 수 있는 IP를 잡아주는 속성이므로, 활성화 되어있으면 외부에서의 접근이 불가능해짐. 주석처리.
#bind-address=127.0.0.1

#재시작 OS-centos7
$systemctl restart mariadb


14)cafe24방화벽 설정
- 방화벽 관리 탭 접속 해서 아래와 같이 설정함.



현재 접속하신 IP는 [116.47.210.241] 입니다.
관리  일반모드  고급모드
서버 IPO/S방화벽 상태관리

1**.**.**.***

CentOS  ON [해제] [방화벽초기화] [포트검색]
INBOUND 접근 정책 (외부에서 내부로 접근: 모든IP)

NO이름프로토콜포트접근허용 IP접근 차단 IP관리
5 mysql tcp 3306 ANY
[Rule 삭제] [차단IP추가]
4 web-ssl tcp 443 ANY
[Rule 삭제] [차단IP추가]
3 ftp tcp 21 ANY
[Rule 삭제] [차단IP추가]
2 http tcp 80 ANY
[Rule 삭제] [차단IP추가]
1 ssh tcp 22 ANY
[Rule 삭제] [차단IP추가]
0 ANY ANY ANY ANY ANY DROP
    1    
INBOUND 접근 정책 (외부에서 내부로 접근: 특정IP)

NO이름프로토콜포트접근허용 IP관리
0 ANY ANY ANY ANY DROP
OUTBOUND 접근 정책 (내부에서 외부로 접근)

NO이름프로토콜포트관리
10 web-ssl tcp 443 [Rule 삭제]
9 http tcp 80 [Rule 삭제]
8 domain udp 53 [Rule 삭제]
7 domain tcp 53 [Rule 삭제]
6 whois tcp 43 [Rule 삭제]
5 time tcp 37 [Rule 삭제]
4 smtp tcp 25 [Rule 삭제]
3 ftp tcp 21 [Rule 삭제]
2 ftp-data udp 20 [Rule 삭제]
1 ftp-data tcp 20 [Rule 삭제]
0 ANY ANY ANY DROP
    1