반응형

*** nginx는 이미 설치되어있다는 가정

 

 

php 설치

// php install
yum -y install http://rpms.remirepo.net/enterprise/remi-release-7.rpm 
yum -y install epel-release yum-utils
yum-config-manager --enable remi-php74
yum install php php-mysql php-fpm

// set address
nano /etc/php-fpm.d/www.conf

listen=localhost:9000 -> listen=/var/run/php-fpm/php-fpm.sock

// start
systemctl start php-fpm
systemctl enable php-fpm.service

// nginx setting
server {
    server_name my_domain;
    client_max_body_size 5G;

    #charset koi8-r;
    access_log  /var/log/nginx/my_service.access.log;

    root /usr/share/nginx/html/my_service;

    location / {
        index index.html index.htm index.php;
    }

    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/my_service$fastcgi_script_name;
        include fastcgi_params;
    }
}

systemctl restart nginx

ERR 403 Page

// 403 Page error
2021/12/20 23:38:06 [error] 2157#2157: *29 "/usr/share/nginx/html/my_service/index.php" is forbidden (13: Permission denied), client: 218.235.68.160, server: my_domain, request: "GET / HTTP/1.1", host: "my_domain"

// dir 및 하위 파일 권한 체크
ls -lZd /service_root/my_service

// dir 및 하위 파일 권한 변경
chcon -R -t httpd_sys_content_t /service_root/my_service

 

ERR mysql :: Connect Error: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

// mysql install
yum -y install http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
yum -y install mysql-community-server 
systemctl start mysqld
systemctl enable mysqld

// find your  temporary password (ex: XcheTa.X-5o1)
/var/log/mysqld.log

// change db password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'XcheTa.X-5o1';
FLUSH PRIVILEGES;
use mysql;
UPDATE user set authentication_string=password('newpassword') where user='root';
-> policy error?
  SET GLOBAL validate_password_policy=LOW;
  UPDATE user set authentication_string=password('newpassword') where user='root';
FLUSH PRIVILEGES;

// mysql exit
quit;

 

필요시 mysql 계정 생성
db생성 하여 쓰면됩니다.

 

ERR -> /install/ajax.install.check.php

// 버전 이슈일 확률이 높음 -> php 7.4 재설치 진행

 

ERR unix:/var/run/php-fpm.sock failed (13: permission)

// /etc/php-fpm.d/www.conf <-- 약간씩 다를 수 있음
user = nginx
group = nginx

listen.owner = nginx
listen.group = nginx
listen.mode = 0660

// 실행
systemctl restart nginx
systemctl restart php-fpm

 

ERR 로그인 에러 / data 접근 권한 에러

// SElinux 에러
// SElinux는 특정 서비스에 대한 권한을 필요한 만큼 허용하고 이외에는 모두 차단하는 정책을 가지고있어, 서비스의 취약성을 이용한 공격이 발생해도 관계된 프로세스나 파일 시스템에 쉽게 접근하지 못하도록 사전에 차단하는 역할을 함.
// 따라서, 완정 중지를 하게되면 보안상 문제가 발생할 수 있음
// 아래와 같이 임시 비활성화 처리가 가능하다.
// Permissive -> 0, Enforcing -> 1
setenforce 0

 

ERR php mb_string

// 관련 내용: https://zetawiki.com/wiki/CentOS_php-mbstring_%EC%84%A4%EC%B9%98


// 확인
php -r "mb_substr();"
-> PHP Fatal error:  Call to undefined function mb_substr() in Command line code on line 1

rpm -qa php-mbstring
yum info php-mbstring | grep Repo
-> Repo        : base

// 설치
yum install php-mbstring -y

// 설치자료 확인
rpm -qa php-mbstring
-> php-mbstring-5.3.3-3.el6_2.8.x86_64


// 재실행
systemctl restart nginx
systemctl restart php-fpm
반응형
반응형

구글에서 제공해주는 도구들을 이용해 체크해보니 운영중인 웹사이트 로딩속도가 어마어마하게 느렸다

모바일 기준으로 19.7

 

경악스러웠다.

당장 손볼수 있는것들을 손봤고 약 2배정도 빠른 속도를 얻어 방법을 공유한다.

 

이미 되어있던 퍼포먼스 관련 설정들

1. 서버 로드밸런스

2. 부분적으로 적용한 이미지 cloud front

 

 

추가한 퍼포먼스 관련 설정들

1. Nginx - gzip

2. Webpack - compression

3. Code spliting

4. 전체 이미지 cloud front 적용

 

이 중에서 가장 쉽고 큰 효과를 얻은것은 gzip이 아닌가싶다

주의할점은 클라이언트와 웹서의 서버가 분리되어있다면 양쪽 모두에 설정해주어야 한다는 점이다.

 

코드는 간결하다. nginx.conf 파일에 아래의 내용을 설정한다.

http {
...

gzip  on;

gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript application/javascript text/xml application/xml application/xml+rss text/javascript;

...
}

 

코드 스플리팅은 react의 lazy/suspense를 이용해서 간단히 설정해주었다.

코드를 너무 작은단위로 나눠도 호출하는 시간에서 손해가 발생하기 때문에 webpack plugin 설정에 아래와같이

최소 크기를 설정해주었다

...,
plugins: [
  ...,
  new webpack.optimize.MinChunkSizePlugin({
    minChunkSize: 512000, // 50kb
  }),
  ...          
]

compression은 역시 plugin 에서 간단히 추가했다.

[
  new CompressionPlugin({
    filename: '[path][base].gz',
    algorithm: 'gzip',
    test: /\.js$|\.css$|\.html$/,
    threshold: 10240, // 10kb
    minRatio: 0.8,
  }),
]

 

반응형
반응형

Error during WebSocket handshake: Unexpected response code: 400

웹소켓 연동 중 이러한에러가 발생 + 서버가 느려지는 현상이 발생했다.

 

해결을 위해서는 nginx의 proxy파트에 추가적으로 다음과 같은 코드를 넣어줘야 한다.

proxy_http_version 1.1; 
proxy_set_header Upgrade $http_upgrade; 
proxy_set_header Connection "upgrade"; 
proxy_set_header Host $host; 

 

반응형

'개발, 코딩 > Nginx' 카테고리의 다른 글

웹사이트 속도 개선방법  (0) 2020.09.25
[Nginx] detect/filter old browser (야호!)  (0) 2020.06.23
반응형

https설정은 할일이 매우많다

 

로그인이 들어가는 순간 그 서버는 거의 필수적으로 https를 사용해야 된다고 생각한다.

 

그래서 관련 포스팅을 해본다.

 

 

기본적으로 https설정은 유료이다.

 

단, Certbot을 사용하면 무료로 설정할 수 있다.

 

Let's encrypt에서 발행해주는 https인증서는 그 수명이 3개월인데, 간단한 설정으로 자동 무한발급을 받을수 있다.

( lets' encrypt의 정책이 바뀌지 않는다면)

 

https://certbot.eff.org/lets-encrypt/ubuntubionic-nginx

 

Certbot - Ubuntubionic Nginx

Different Internet services are distinguished by using different TCP port numbers. Unencrypted HTTP normally uses TCP port 80, while encrypted HTTPS normally uses TCP port 443. To use certbot –webroot, certbot –apache, or certbot –nginx, you should have an

certbot.eff.org

 

위의 사이트에서 자신의 os - web server에 맞게 검색하여 가이드라인을 따른다면

 

세팅을 아주 무난히 마칠수 있다.

 

문제는, 늘 세팅 이후의 나의 환경에 맞게 설정하는 부분이다.

 

다들, 그냥 이렇게 저렇게 하라고만 할뿐 어떻게 내 환경에 맞게 설정해야 될지는 아무도 알려주지 않아 내가 적는다.

 

0. 최소한의 웹서버 설정

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;
        root /home/ubuntu/myproject/build;
        index index.html index.htm index.nginx-debian.html;

        server_name mydomain;

        location / {
                try_files $uri $uri/ =404;
        }
}

 

1. Http요청 Https redirect시키기

 

웹의 기본 요청방식(통신방식)은 http이기 때문에, 사용자들의 http요청을 https로 redirect시킬 필요가 있다.

 

/etc/nginx/sites-available/defulat 파일에서 설정을 해보도록 하자 (본 파일은  nginx.conf에 include됨)

 

server 블록을 하나 만들어 http요청을 모두  https로 redirect시킬 수 있다.

server {
    server_name mydomain;

    if ($host = mydomain) {
        return 301 https://mydomain
    }

    return 404;
}

 

2. 내 프로젝트 붙이기

 

이제 막, 서버를 개설중인 것이라면 내 프로젝트를 nginx/apache서버에 붙여줄 필요가 있다.

 

어떻게 만들어졌냐에 따라 크게 달라지지만

 

먼저, html로 만든 간단한 웹사이트의 경우이다.

server {
    client_max_body_size 100M; // 너무 큰 요청은 곤란하다..

    server_name mydomain;
    root /var/www/html; // 내 프로젝트 위치를 잡아주면됨. 특히, 그중에서도 index.html의 위치
    index index.html // 위에서 말한 index.html 파일명을 명시

    // https 설정!!
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mydomain/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

 

다음으로, react로 만든 프로젝트이다.

...

server {
  server_name mydomain;
  root /home/ubuntu/myproject/build; // 내 프로젝트 위치를 잡아주면됨. 특히, 그중에서도 index.html의 위치
  index index.html // 위에서 말한 index.html 파일명을 명시


  location / {
  	try_files $uri $uri/ /index.html;
  }

  location ~* \.(?:manifest|appcache|html?|xml|json|service-worker\.js)$ {
  	expires -1;
  }

  location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
    expires 1M;
    access_log off;
    add_header Cache-Control "public";
  }

  location ~* \.(?:css|js)$ {
    expires 1y;
    access_log off;
    add_header Cache-Control "public";
  }

  // https 설정!!
  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/mydomain/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/mydomain/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

 

반응형