오늘은 nginx 웹 서버를 셋팅하는 작업을 진행 할거다!
nginx 에대한 기본 설명을 좀 하고 셋팅 과정을 천천히 진행해보자!
nginx 는 아파치와 같은 웹서버중 하나이며, 가볍고 여러요청을 한번에 처리가 가능한 장점을 가진 웹서버이다.
동작이 단순하고 전달자 역할만 해서 동시접속에 특화가 되어있다! 구동방식은 event driven (비동기처리방식)인데
요청이 들어올시 어떤 동작을 해야하는 지만 알려주고 다른 요청을 처리하는 방식이다.
cpu와 관계없이 모든 입출력들을 전부 이벤트 리스너로 전달하기 때문에 흐름이 끊기지 않고 응답이 빠르게 진행되어 1개의 프로세스로 보다 더빠른 작업을 가능하게 한다. 여기서 웹서버는 무엇이냐?
웹서버의 역할은 html, css 자바스크립트, 이미지 와 같은 정적인 정보를 사용자 에게 전송해주는 역할을 한다.
또한 리버스 프록시의 역할도 한다! 리버스 프록시는 기존의 포워드 프록시가 클라이언트 앞단에서 요청을 처리한다면, 내부망의 서버 앞단에서 요청을 처리하는데 이 리버스 프록시의 장점은 보안에 강점이 있기 때문이다. was 웹어플리케이션 서버는 대부분 db서버와 연결되어있다. was 가 최전방에 있으면 보안에 취약해진다.
위 그림처럼 바로 디비랑 연결이 되어있어서 보안이 매우 취약 한데 여기서 웹서버 인 nginx 를 두면 웹서버가 웹어플리케이션 서버랑 통신해서 결과를 클라이언트에게 제공하면 보안에 취약점을 잡을 수있다.! 서론이 너무 길었다 이제 셋팅을 해보도록 하겟다.
터미널을 킨 후 ssh로 개발 서버로 진입
비번을입력 후
NGINX.CONF 파일 찾아내는 명령어 -> sudo find / -name nginx.conf
터미널창에 입력해준다.( nginx 를 이미 개발서버에 설치 한 과정에서 설명)
찾은 후에
- 보통 /etc/nginx/* 아래에 설정파일이 위치해있고, 로그파일은 /var/log/nginx/* 에 위치해있다.
ls 로 항목들을 보면
Nginx.conf(접속자 수, 동작 프로세스 수 등 퍼포먼스에 관한 설정들)
Sites-enabled( 활성화된 사이트들의 설정 파일들이 위치한다. 존재 하지 않은 경우 직접 디렉토리 생성 가능)
등등 이 있다 우선 우리는
Sites-available ( 설정을 저장하는 곳이다. 여기에 설정을 만든 것은 실제로 nginx에 반영되지는 않습니다. 반영하기 위해서는 sites-enabled에 설정파일을 복사 또는 심볼릭링크를 걸어준다.)
nginx의 폴더 안을 들여다 보면 sites-available과 sites-enabled라는 폴더가 존재한다. 이 폴더들은 한 웹서버에서 여러가지 웹 서비스를 다른 도메인으로 운영 할 때를 대비해서 있는 폴더라고 이해하면 된다.
sites-available에는 각 도메인의 고유 설정 파일을 저장 해 두고, sites-enabled에 심볼릭 링크를 작성 혹은 삭제 함으로서 손쉽게 웹 서비스를 실행 혹은 중단 시키는 것이 가능하다.
등등으로 이해하고 vim 을 사용하여
Nginx 가상서버 파일 작성
nginx.conf vim으로 수정하기(메인 설정 파일)
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
server {
listen 8000;
server_name tmng.tablenjoy.com;
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
index index.html;
#charset koi8-r;
#access_log logs/tadmin_html/host.access.log main;
#root /home/dev/hitable2020-frontend-manager/dist;
location / {
root /home/dev/hitable2020-frontend-manager/dist;
index index.html;
try_files $uri $uri/ @rewrites;
}
}
server {
listen 8003;
listen [::]:8003;
server_name tapi.tablenjoy.com;
ssl on;
ssl_certificate /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.crt;
ssl_certificate_key /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.key;
ssl_prefer_server_ciphers on;
error_page 497 https://$host:8003$request_uri;
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
if ($request_method = 'OPTIONS') {
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header Connction "";
proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
}
server {
listen 8002;
server_name tmng.tablenjoy.com;
ssl on;
ssl_certificate /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.crt;
ssl_certificate_key /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.key;
ssl_prefer_server_ciphers on;
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
index index.html;
#charset koi8-r;
#access_log logs/tadmin_html/host.access.log main;
location / {
root /home/dev/hitable2020-frontend-brand-admin/dist;
index index.html;
try_files $uri $uri/ @rewrites;
}
}
server {
listen 8005;
server_name tmobile.hi-table.com;
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
index index.html;
#charset koi8-r;
#access_log logs/tmobile_html/host.access.log main;
location / {
root /home/dev/hitable2020-frontend-store-manager/dist;
index index.html;
try_files $uri $uri/ @rewrites;
}
}
server {
listen 7400;
listen [::]:7400;
server_name tapi.tablenjoy.com;
ssl on;
ssl_certificate /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.crt;
ssl_certificate_key /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.key;
ssl_prefer_server_ciphers on;
error_page 497 https://$host:7400$request_uri;
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
if ($request_method = 'OPTIONS') {
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header Connction "";
proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:3000;
}
}
server {
listen 8001 default_server;
listen [::]:8001 default_server;
server_name _;
ssl on;
ssl_certificate /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.crt;
ssl_certificate_key /home/dev/인증서/star_tablenjoy_com/star_tablenjoy_com.key;
ssl_prefer_server_ciphers on;
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
if ($request_method = 'OPTIONS') {
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header Connction "";
proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:3000;
}
}
}
113,0-1 23%
listen 은 port 설정 하는 부분이다. 기본 포트는 80
root는 document root 설정 하는 부분 디폴드 는 html 디렉토리.
proxy_pass 설정은 nginx 뒷 단에 was 가 존재하는 경우이며, 확장자 기반으로 요청 처리를 분리하는 것 location / 이렇게 되어있으면 127.0.0.1:3000 으로 넘기는것이다.
server_name 도메인이름 처럼 바꿔주게 되는데 방문자가 어떤 주소로 들어오냐에따라 해당 도메인 이름을 가진 server{...} 블록이 처리한다.
- http 블록
http 블록은 server, location 블록을 포함한다. http 블록을 여러개 생성하여 관리할 수 있지만, 권장사항은 아니다.(권장사항은 http 블록을 하나만 생성하는 것) (oop 상위 클래스 개념으로 생각하면 쉽다.)
-서버 블록
- 하나의 웹사이트를 선언하는 데 사용된다. 가상 호스팅(Virtual Host)의 개념이다.
- location 블록
서버의 하위단 블록으로 특정 경로, 즉 특정 url을 처리하는 단위이다.
예를 들어 개발 소개 블로그 (www.dev.com) 에서
www.dev.com/nginx (nginx를 소개하는 카테고리)
www.dev_moster.com/apache (apache를 소개하는 카테고리)
로 나누고 싶을때 사용할 수 있다.
- events 블록
http, server, location 블록과 엮이지 않고 독립적은 블록이다.
주로, 네트워크 동작 방법을 설정한다.
예를 들어
events {
worker_connections 100;
}
이렇게 worker_connections 을 100으로 설정하면,
이 웹서버에 한번에 최대 100명이 동시에 접근을 할 수 있다는 것을 의미한다.
ssl 부분은 도메인 인증서, 체인 인증서, 루트 인증서를 발급 완료받은걸 서버에 업로드한다. 그 경로를 적어주면 연결된다.!
ssl_certificate /root/ssl/nginx-ssl.crt;
ssl_certificate_key /root/ssl/nginx-ssl.key;
위에처럼 위치를 지정해주면 된다.
추가적으로 http 로 접속 시 https 로 리다이렉트 하는 부분은 아래와 같이 코드를 추가하면된다.
return 301 https://$host$request_uri;
아래 리스타트 명령어로 재실행 시킨다.
sudo systemctl restart nginx
site available 에서 설정파일 추가
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;
#}
}
server {
listen 8005;
listen [::]:8005;
root /home/dev/hitable2020-frontend-manager/dist;
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
}
}
server {
listen 8001 ssl;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location ~/.well-known {
allow all;
}
}
여기서 심볼릭 링크를 걸어줘야한다 site-adailable/ 에서 만든 사이트를 site-enabled/에 추가해야 활성화가 된다.
site-adailable/ 에 추가한 사이트를 site-enabled/에 심볼릭 링크하여 사이트를 활성화 할 수 있다.
심볼릭 링크랑 윈도위의 바로가기이다.
site-enabled 추가
#
# 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;
#}
}
server {
listen 8005;
listen [::]:8005;
root /home/dev/hitable2020-frontend-manager/dist;
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
}
}
server {
listen 8001 ssl;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location ~/.well-known {
allow 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.
#
conf.d 폴더
- nginx.conf에서 include로 불러올 수 있는 conf 파일 저장 폴더.
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#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;
}
# 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
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$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;
#}
}
좀더 디테일하게 하고 싶으면 검색을 하면서 추가적으로 셋팅을 더넣으면 될것같다 내부아이피로 포트를 타면 페이지가 잘뜨는것을 확인할수있다~ 내부아이피타임으로 설정은 추가적으로 들어가면 내부에서 와이파이가 연결되어있을경우에만 회사에서 사용가능한 개발서버가 열린다~
101 번서버에 추가적으로 nginx 가 잘연결됐다.
'DevOps > nginx' 카테고리의 다른 글
두개의 서버 설정 - Local 윈도우 기준 (0) | 2024.08.27 |
---|