nginx.conf 에 gzip 설정 추가


http {

    

   ......


    # Gzip Settings

    gzip on;

    #gzip_static on;

    gzip_disable "MSIE [1-6]\.(?!.*SV1)"; 

    gzip_vary on;

    gzip_proxied any;

    gzip_comp_level 6;

    gzip_min_length 512;

    gzip_buffers 16 8k;

    gzip_http_version 1.1;

    gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml  application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml;


Tomcat에 압축을 적용하려면 다음 링크 참고 


http://misoin.tistory.com/46

참고용 (gzip, minify js/css, robots.txt 등등)


# yum install perl-devel perl-ExtUtils-Embed

# yum install cpan

# cpan JavaScript::Minifier::XS

# cpan CSS::Minifier::XS


nginx 설치시 --with-http_perl_module 포함


# ./configure --prefix=/usr/local/nginx \

> --sbin-path=/usr/local/nginx/sbin/nginx \

> --conf-path=/usr/local/nginx/conf/nginx.conf \

> --pid-path=/log/nginx/nginx.pid \

> --error-log-path=/log/nginx/error.log \

> --http-log-path=/log/nginx/access.log \

> --with-http_ssl_module --with-http_perl_module



 

nginx.conf


user ec2-user;

# Server CPU core count

worker_processes  2;


pid        /data/nginx/nginx.pid;


events {

    # connection count per worker_process (concurrent count = worker_processes * worker_connections)

    worker_connections  1024;

    multi_accept on;

    use epoll;

}


http {

    # Let NGINX get the real client IP for its access logs

    #set_real_ip_from 127.0.0.1;

    #real_ip_header X-Forwarded-For;


    include /usr/local/nginx/conf/mime.types;

    default_type application/octet-stream;


    # Logging Settings

    access_log /log/nginx/access.log;

    error_log /log/nginx/error.log;

 

    # Log Format

    log_format main '$remote_addr - $remote_user [$time_local] '

    '"$request" $status $body_bytes_sent "$http_referer" '

    '"$http_user_agent" "$http_x_forwarded_for"';


    # Basic Settings

    sendfile on;

    tcp_nopush on;

    tcp_nodelay on;

    keepalive_timeout 20;

    client_max_body_size 15m;

    client_body_timeout 60;

    client_header_timeout 60;

    client_body_buffer_size  1K;

    client_header_buffer_size 1k;

    large_client_header_buffers 4 8k;

    send_timeout 60;

    reset_timedout_connection on;

    types_hash_max_size 2048;

    server_tokens off;


    # server_names_hash_bucket_size 64;

    # server_name_in_redirect off;


    # Gzip Settings

    gzip on;

    #gzip_static on;

    gzip_disable "MSIE [1-6]\.(?!.*SV1)"; 

    gzip_vary on;

    gzip_proxied any;

    gzip_comp_level 6;

    gzip_min_length 512;

    gzip_buffers 16 8k;

    gzip_http_version 1.1;

    gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml  application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml;


    perl_modules perl;

    perl_require Minify.pm;

 

    # Virtual Host Configs

    #include /etc/nginx/conf.d/*.conf;

    #include /etc/nginx/sites-enabled/*;


    server {

        # Configure the domain

        listen       80;

        server_name  localhost;

port_in_redirect off;

server_tokens off;

autoindex off;


        client_max_body_size 15m;

        client_body_buffer_size 128k;


root /home/test;


# Define default caching of 24h

expires 86400s;

add_header Pragma public;

add_header Cache-Control "max-age=86400, public, must-revalidate, proxy-revalidate";


location / {

   index  index.html index.htm;

        }


        location ~* \.css$ {

            try_files $uri.min.css @minify_css;

   expires 31536000s;

   access_log off;

   log_not_found off;

   add_header Pragma public;

   add_header Cache-Control "max-age=31536000, public";

        }


        location ~* \.js$ {

            try_files $uri.min.js @minify_js;

   expires 31536000s;

   access_log off;

   log_not_found off;

   add_header Pragma public;

   add_header Cache-Control "max-age=31536000, public";

        }


        location @minify_css {

            perl Minify::css_handler;

        }


        location @minify_js {

            perl Minify::js_handler;

        }


# Aggressive caching for static files

# If you alter static files often, please use 

# add_header Cache-Control "max-age=31536000, public, must-revalidate, proxy-revalidate";

location ~* \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|otf|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|t?gz|tif|tiff|ttf|wav|webm|wma|woff|wri|xla|xls|xlsx|xlt|xlw|zip)$ {

expires 31536000s;

access_log off;

log_not_found off;

add_header Pragma public;

add_header Cache-Control "max-age=31536000, public";

}


# Deny access to hidden files

location ~ /\. {

deny all;

access_log off;

log_not_found off;

}


# Don't log robots.txt requests

location = /robots.txt {

allow all;

log_not_found off;

access_log off;

}


# Deliver a static 404

#error_page 404 /404.html;

#location  /404.html {

# internal;

#}


        # Deliver 404 instead of 403 "Forbidden"

error_page 403 = 404;


        # redirect server error pages to the static page /50x.html

        #

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   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;

        #}

    }



    # another virtual host using mix of IP-, name-, and port-based configuration

    #

    #server {

    #    listen       8000;

    #    listen       somename:8080;

    #    server_name  somename  alias  another.alias;

    #    server_name localhost;


    #    location / {

    #        root   /home/ec2-user/web;

    #        index  index.html index.htm;

    #    }

    #}


    # HTTPS server

    #

    #server {

    #    listen       443;

    #    server_name  localhost;


    #    ssl                  on;

    #    ssl_certificate      cert.pem;

    #    ssl_certificate_key  cert.key;


    #    ssl_session_timeout  5m;


    #    ssl_protocols  SSLv2 SSLv3 TLSv1;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;

    #    ssl_prefer_server_ciphers   on;


    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}


}




Minify.pm


package Minify;

use nginx;

use JavaScript::Minifier::XS;

use CSS::Minifier::XS;

 

sub css_handler {

    my $r = shift;

    my $cache_file = $r->filename . ".min.css";

    my $filename = $r->filename;

    local $/=undef;

 

    return DECLINED unless -f $filename;

 

    open(INFILE, $filename) or die "Error reading file: $!";

    my $css = <INFILE>;

    close(INFILE);

 

    open(OUTFILE, '>' . $cache_file) or die "Error writing file: $!";

    print OUTFILE CSS::Minifier::XS::minify($css);

    close(OUTFILE);

 

    $r->send_http_header('text/css');

    $r->sendfile($cache_file);

    return OK;

}

 

sub js_handler {

    my $r = shift;

    my $cache_file = $r->filename . ".min.js";

    my $filename = $r->filename;

    local $/=undef;

 

    return DECLINED unless -f $filename;

 

    open(INFILE, $filename) or die "Error reading file: $!";

    my $js = <INFILE>;

    close(INFILE);

 

    open(OUTFILE, '>' . $cache_file) or die "Error writing file: $!";

    print OUTFILE JavaScript::Minifier::XS::minify($js);

    close(OUTFILE);

 

    $r->send_http_header('application/javascript');

    $r->sendfile($cache_file);

    return OK;

}

 

1;


robot.txt


User-agent: *

Disallow: /resources/



perl을 이용한 minify에 대한 참고 자료는 아래 링크에서 도움..


http://www.thatdoesntwork.net/tech-tricks/automatic-minification-with-nginx/

http://wiki.nginx.org/NginxEmbeddedPerlMinifyJS

tomcat + nginx 연동하기에서 nginx를 설치했었다.

OpenSSL을 이용해 Self-Signed SSL 인증서 만들기에서 자체 서명된 인증서를 생성했다.


 

이제, nginx에서 ssl를 적용해보자.


# cd /usr/local/nginx
# vi conf/nginx.conf

아랫부분에 # HTTPS server 섹션을 찾아서 주석을 풀고 수정을 한다.

    # HTTPS server
    #       
    server {
        listen       443;
        server_name  localhost; 
        
        ssl                  on;
    #   ssl_certificate      cert.pem;
    #   ssl_certificate_key  cert.key;
        ssl_certificate      /usr/local/ssl/www.xxxx.co.kr.crt;
        ssl_certificate_key  /usr/local/ssl/www.xxxx.co.kr.key;
        
        ssl_session_timeout  5m;
        
        ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers   on;
        
        location / {
            root   html; 
            index  index.html index.htm;
        }
    }


설정 끝.. 간단하다.
nginx의 설정파일을 새로 읽어들이면 된다.


# sbin/nginx -s reload


이제 브라우저에서 https://xxx.xxx.xxx.xxx 를 하면 ssl이 적용된 화면을 볼 수 있다.

먼저 tomcat (http://tomcat.apache.org/) 을 설치하자.


톰캣 7버전을 다운로드 후 압축 해제

# cd /usr/local/src
# wget http://apache.tt.co.kr/tomcat/tomcat-7/v7.0.27/bin/apache-tomcat-7.0.27.tar.gz
# tar zxvf apache-tomcat-7.0.27.tar.gz
# cp -Rf apache-tomcat-7.0.27 /usr/local/tomcat
# cd /usr/local/tomcat/
# ll
total 116
drwxr-xr-x 2 root root 4096 Jun 19 07:44 bin
drwxr-xr-x 2 root root 4096 Jun 19 07:44 conf
drwxr-xr-x 2 root root 4096 Jun 19 07:44 lib
-rw-r–r– 1 root root 56797 Jun 19 07:44 LICENSE
drwxr-xr-x 2 root root 4096 Jun 19 07:44 logs
-rw-r–r– 1 root root 1192 Jun 19 07:44 NOTICE
-rw-r–r– 1 root root 8826 Jun 19 07:44 RELEASE-NOTES
-rw-r–r– 1 root root 10597 Jun 19 07:44 RUNNING.txt
drwxr-xr-x 2 root root 4096 Jun 19 07:44 temp
drwxr-xr-x 7 root root 4096 Jun 19 07:44 webapps
drwxr-xr-x 2 root root 4096 Jun 19 07:44 work


GET 통해 한글 데이터를 받을때 서버에서 URL을 UTF-8로 인코딩하도록 설정


# vi conf/server.xml

<Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443"

               maxThreads="150"

               minSpareThreads="25"

               maxSpareThreads="75"

               enableLookups="false"

               acceptCount="100"

               disableUploadTimeout="true"

               URIEncoding="UTF-8" />

# vi /etc/profile

CATALINA_HOME=/usr/local/tomcat
export CATALINA_HOME
PATH=$PATH:$JAVA_HOME/bin:$CATALINA_HOME/bin
export PATH
CLASSPATH=$CLASSPATH:$JAVA_HOME/lib:$CATALINA_HOME/lib
export CLASSPATH

# source /etc/profile


톰캣 실행

# bin/startup.sh

종료는

# bin/shutdown.sh

확인은

http://XXX.XXX.XXX.XXX:8080


 



다음으로 nginx (http://nginx.org/) 를 설치해보자.


현재 안정버전은 1.2.1, 개발버전은 1.3.1

# wget http://nginx.org/download/nginx-1.2.1.tar.gz
# tar zxvf nginx-1.2.1.tar.gz
# cp -Rf nginx-1.2.1 /usr/local/nginx
# cd /usr/local/nginx/
# ll
total 560
drwxr-xr-x 6 root root 4096 Jun 19 08:22 auto
-rw-r–r– 1 root root 207988 Jun 19 08:22 CHANGES
-rw-r–r– 1 root root 317085 Jun 19 08:22 CHANGES.ru
drwxr-xr-x 2 root root 4096 Jun 19 08:22 conf
-rwxr-xr-x 1 root root 2345 Jun 19 08:22 configure
drwxr-xr-x 3 root root 4096 Jun 19 08:22 contrib
drwxr-xr-x 2 root root 4096 Jun 19 08:22 html
-rw-r–r– 1 root root 1365 Jun 19 08:22 LICENSE
drwxr-xr-x 2 root root 4096 Jun 19 08:22 man
-rw-r–r– 1 root root 49 Jun 19 08:22 README
drwxr-xr-x 8 root root 4096 Jun 19 08:22 src


컴파일 옵션을 참조 (http://nginx.org/en/docs/install.html)
–with 옵션에 ssl, pcre, zlib 가 등장하므로. 이것들을 미리 설치해주자.

# yum install openssl openssl-devel
# yum install pcre pcre-devel
# yum install zlib zlib-devel


아래 *-path= 옵션들의 경로는 입력하지 않을 경우 nginx의 기본값이기도 하다.

# ./configure –-prefix=/usr/local/nginx \
> –-sbin-path=/usr/local/nginx/sbin/nginx \
> –-conf-path=/usr/local/nginx/conf/nginx.conf \
> -–pid-path=/usr/local/nginx/logs/nginx.pid \
> -–error-log-path=/usr/local/nginx/logs/error.log \
> -–http-log-path=/usr/local/nginx/logs/access.log \
> -–with-http_ssl_module
# make && make install


nginx 구동은

 # sbin/nginx


별다른 메시지가 없다면 정상 구동이 된것이다.

브라우저에서 http://XXX.XXX.XXX.XXX 를 하면 썰렁한 “Welcome to nginx!” 가 보인다.



종료는 # sbin/nginx -s stop 혹은 # sbin/nginx -s quit
설정파일 등의 수정 후 재적용은 # sbin/nginx -s reload
로그파일을 다시 열려면 # sbin/nginx -s reopen



이제, tomcat과 nginx를 연동해보도록 하자.


정적 자원(html, js, css, image 등)은 기본적으로 nginx 를 이용하고,
동적 처리되는 부분에서는 tomcat를 사용하도록 하는 proxy 설정 방식이다.


# vi conf/nginx.conf

.
.
http {
.
.
.
    upstream backend {
        server  localhost:8080 
    }
.
.
.
    server {
        listen       80;
        server_name  localhost;
.
.
.
        location / {
            root   html;
            index  index.html index.htm;
        }
.
.
.
        location /servlet {
            proxy_pass      http://backend/servlet;
            index           index.jsp;
        }

        location /manager {
            proxy_pass      http://backend/manager;
            index           index.jsp;
        }
    }
.
.
. 

}


저장하고 설정정보를 다시 적용..


# sbin/nginx -s reload


이 경우, http://localhost/servlet/ 으로 들어오는 요청을 http://localhost:8080/servlet/ 으로 가도록 한다.

자세한 설정은 http://nginx.org/en/docs/ 와 http://wiki.nginx.org/Configuration 를 참고할 수 있다.


+ Recent posts