Programming/PHP

웹개발 준비 1 - nginx + php 설정하기

minarae7 2014. 11. 19. 13:56
728x90
반응형

최근 몇 년간 가장 즐겨 사용하는 구성은 다음과 같다.


OS: ubuntu

web engine: nginx

Language : php

Framework: Codeigniter

Css: bootstrap

DB: mysql


이전에는 nginx 대신 apache를 사용했었는데 apache는 설정해야 하는 내용도 너무 많고 기능이 많아지면서 무거워지는 등의 단점이 눈에 띈다. 대신 nginx는 정말 간단하게 설정을 진행할 수 있으며 가볍게 사용할 수 있는 엔진이다.


그리고 이전에는 php로 웹 개발을 진행할 때 대부분 혼자 개발하는 일이 많았기 때문에 프레임워크를 사용할 일이 없었다. 프레임워크를 익힐 시간에 한줄이라도 더 코딩하자는 주의였기 때문이다.


그러다가 Codeigniter를 접하고 사용하기 시작하면서 프레임워크의 장점을 최대한 사용하기 위해서 노력하고 있다. 프레임워크를 익혀서 사용하는 것이 날코딩 하는 것보다 훨씬 효율적이라는 사실을 뒤늦게 깨달은 것이다.


Bootstrap은 Twitter에서 제공하는 Css 프레임워크라고 할 수 있다. 많지 않은 코드를 익히므로 해서 좀 더 보기 좋은 웹페이지를 편리하게 구축할 수 있게 해준다.


개인적으로 서버를 설정하면 항상 하는 작업들이지만 자주 하는 작업이 아니기 때문에 늘 구글을 통해서 검색한 후에 서버를 설정하기 때문에 나같은 설정을 선호하는 사람들을 위해서 기록을 남기도록 한다.


운영체제는 Ubuntu를 사용하고 OS 설치 후에 아무것도 설치 되지 않았다는 것을 가정하고 기록을 남기도록 한다.


1. nginx 설치


ubuntu에서 설치 및 설정 작업을 할 때는 귀찮아서 root 권한을 얻어서 작업하도록 한다.


root 권한을 얻는 옵션은 여러가지가 있지만 


sudo -s


이 옵션을 주로 사용한다.


root 권한을 얻은 먼저 nginx를 설치한다.


apt-get install nginx


이렇게 설치하고 나면 아무 설정을 안하고도 웹페이지가 뜨는 것이 정상이다.


example.com 처럼 도메임을 치고 들어갔을 때


"It's work"


라는 메시지가 나온다. 이것은 nginx의 기본 페이지 메시지이다.


2. php 설치


다음은 php를 설치하도록 한다.


이전에 apache를 사용하여 php를 설치할 때는 php5등의 라이브러리를 사용하였다. 하지만 nginx를 사용할 경우는 설치하는 패키지가 약간 다르다.


기본이 되는 php5는 똑같이 설치되지만 이 녀석이 주가 아니고 php-fpm이라는 녀석이 주가 된다.


설치 명령어는 다음과 같다.


apt-get install php5-fpm php5-cli php5-mysql


php5-mysql은 어차피 DB 연결을 위해서 필요한 녀석이기 때문에 똑같이 설치하게 된다.


이렇게 하고 의존성에 걸려서 설치되는 애들은 다 설치해주면 된다.


apache는 구동될 때 php 모듈을 가지고 올라가서 실행하기 때문에 php를 독립적으로 실행할 필요가 없이 apache만 실행하면 php도 같이 작동된다.


하지만 nginx는 php 모듈과 독립적으로 실행된다. 따라서 php는 독립된 서비스로 실행시켜줄 필요가 있다. 이때 사용하는 서비스가 php5-fpm이라는 패키지이다.


일단 기본 설정은 나중에 하기로 하고 다음 명령어가 실행이 되는지만 테스트해보도록 한다.


service nginx restart

3. nginx 설정하기


이제 nginx의 설정 파일을 설정할 차례이다.


다른 설정 파일도 많지만 도메인에 따라서 다른 경로를 root로 하도록 하는 설정만 주로 사용한다.


그 외의 설정을 잘 바꾸지 않는다.


다음은 /etc/nginx/sites-available/default 파일의 최초 내용이다.


# You may add here your
# server {
#	...
# }
# statements for each of your virtual hosts to this file

##
# 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.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

server {
	#listen   80; ## listen for ipv4; this line is default and implied
	#listen   [::]:80 default ipv6only=on; ## listen for ipv6

	root /usr/share/nginx/www;
	index index.html index.htm;

	# Make site accessible from http://localhost/
	server_name localhost;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to index.html
		try_files $uri $uri/ /index.html;
		# Uncomment to enable naxsi on this location
		# include /etc/nginx/naxsi.rules
	}

	location /doc/ {
		alias /usr/share/doc/;
		autoindex on;
		allow 127.0.0.1;
		deny all;
	}

	# Only for nginx-naxsi : process denied requests
	#location /RequestDenied {
		# For example, return an error code
		#return 418;
	#}

	#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/www;
	#}

	# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
	#
	#location ~ \.php$ {
	#	fastcgi_split_path_info ^(.+\.php)(/.+)$;
	#	# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
	#
	#	# With php5-cgi alone:
	#	fastcgi_pass 127.0.0.1:9000;
	#	# With php5-fpm:
	#	fastcgi_pass unix:/var/run/php5-fpm.sock;
	#	fastcgi_index index.php;
	#	include fastcgi_params;
	#}

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


# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#	listen 8000;
#	listen somename:8080;
#	server_name somename alias another.alias;
#	root html;
#	index index.html index.htm;
#
#	location / {
#		try_files $uri $uri/ /index.html;
#	}
#}


# HTTPS server
#
#server {
#	listen 443;
#	server_name localhost;
#
#	root html;
#	index index.html index.htm;
#
#	ssl on;
#	ssl_certificate cert.pem;
#	ssl_certificate_key cert.key;
#
#	ssl_session_timeout 5m;
#
#	ssl_protocols SSLv3 TLSv1;
#	ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
#	ssl_prefer_server_ciphers on;
#
#	location / {
#		try_files $uri $uri/ /index.html;
#	}
#}

다음은 php와 codeigniter를 사용하기 위해서 설정이다. 중요한 부분은 주석으로 설명하도록 하고 설명은 생략한다.



server {
	#listen   80; ## listen for ipv4; this line is default and implied
	#listen   [::]:80 default ipv6only=on; ## listen for ipv6

	client_max_body_size 10M;

	# Make site accessible from http://localhost/
	server_name	domain.com;	# 연결한 도메인 정보, 여러개 사용 가능
	access_log		/var/log/nginx/domain.com.access.log; # access 로그 파일 지정
	error_log		/var/log/nginx/domain.com.error.log;#error 로그 파일 지정

	proxy_redirect   off;
	charset          utf-8;

	location / {
		try_files $uri $uri/ /index.php?/$request_uri;	# codeigniter에서 index.php를 생략할 경우를 위해서 rewrite하도록 설정
		root   /data/www/domain.com;	# web root 디렉토리 지정
		index  index.php;	# index 파일 이름 지정
		expires 0d;
	}

	location ~ \.php($|/) {	# php을 호출할 경우 php 서비스로 연결시켜주는 설정
		fastcgi_connect_timeout 600s;
		fastcgi_read_timeout 600s;
		fastcgi_send_timeout 600s;

		root	/data/www/domain.com;	# php 파일의 루트 디렉토리, web 루트와 다르게 지정 가능

		fastcgi_pass 127.0.0.1:9000;
		fastcgi_index index.php;
		fastcgi_param  SCRIPT_FILENAME  /data/www/domain.com$fastcgi_script_name;
		include fastcgi_params;
	}
}

이렇게 해서 기본적인 설정을 하였다. 설정이 완료되었다면 nginx를 재시작 혹은 설정파일을 로딩하여 설정을 적용한다.


service nginx restart/reload

restart와 reload 둘 중 하나를 하면 된다.


그리고 정상적으로 페이지가 열리는지 확인하면 된다.


만약 default 파일이 아닌 다른 파일로 설정을 추가하였다면 파일을 심볼릭링크를 하여야 한다.

(예를 들어 도메인 별로 설정파일을 관리할 경우 domain.com이라는 파일을 생성하여 파일을 생성할 수 있다.)


ln -s /etc/nginx/sites-available/domain.com /etc/nginx/sites-enabled/domain.com


링크를 걸고 나서 다시 nginx 재시작하면 된다.


이렇게 해서 기본적인 설정을 마치도록 한다.


다음에 이어서 codeigniter를 설정하는 방법에 대해서 기록하도록 하겠다.


[참고] http://www.lonelycoder.be/nginx-php-fpm-mysql-phpmyadmin-on-ubuntu-12-04/

728x90
반응형