본문 바로가기

인프라/MW

Apache

아파치에 대해서 간략하게 소개를 하도록하겠다.

 

아파치는 웹 브라우저를 통해서 사용자들이 홈페이지에 접속을 위한 관문이자 이런 방문자들에게

 

http 프로토콜을 이용하여 자원을 보여주기 위한 기능을 가진 하나의 서버이자 소프트웨어이다.

 

아파치에 대한 상세한 내용은 아파치를 참고하면 되겠다.

 

일반적인 아파치하면 생각나는 것은 이것이겠지만

 

 

AH-64D_Apache_Longbow.jpg

 

절대로 아니다.

 

IT에 입문하였다면 한번쯤은 접해보았을 것이기에 잡다한 이야기는 여기까지하고,

 

apache를 접하면서 만나볼 내용에 대해서 차례대로 기술하겠다.

 


APACHE Compile 설치방법(WEB/Install)

더보기

1. apache 설치를 위한 계정 생성 & 권한부여(사전준비)

#- apache 계정 생성
sudo useradd apache -b /home -s /bin/bash

#- 현재 접속 계정이 root일 시
sudo echo "apache1234\!" | passwd --stdin apache

#- 현재 접속 계정이 root가 아닐 시
sudo passwd apache
apache1234!

#- 계정권한조율은 References(Sudoers)를 참고
설정이유 : * apache 계정으로 package 설치를 편하게 하기위해
          * 설정 하고 싶지 않을 시, root권한으로 작업 진행
sudo vi /etc/sudoers
apache  ALL=(ALL)       NOPASSWD:ALL

 

/etc/sudoers root권한 사용을 위한 특정계정 sudo 권한 부여

 

 

export ID=`whoami`
export BASE_DIR=`cat /etc/passwd|grep ${ID}|cut -f6 -d ':'`

 

vi ${BASE_DIR}/.bash_profile

## Edit Server Env Setting
export ID=`whoami`
export BASE_DIR=`cat /etc/passwd|grep ${ID}|cut -f6 -d ':'`
export PS1='[`id -nu`@`hostname`:$PWD]# '
export LANG=ko_KR.utf-8

stty erase "^H" kill "^U" intr "^C" eof "^D" susp "^Z" cs8 -ixany -parenb -istrip

## directory paths
export WEB_DIR=${BASE_DIR}/appsw/httpd-2.4.34
export APP_DIR=${BASE_DIR}/apache
export AP_DIR=${BASE_DIR}/web

alias webstart='${APP_DIR}/bin/apachectl start'
alias webstop='${APP_DIR}/bin/apachectl stop'

 

계정 .bash_profile 환경변수 설정정보

 

변경된 환경변수 적용

source ${BASE_DIR}/.bash_profile

 

2. 다운로드/설치 경로지정

sudo yum install expat-devel
sudo yum install libpcre*
sudo yum install gcc-c++
sudo yum install autoconf
sudo yum install libtool
sudo yum install openssl-devel

 

mkdir -p ${BASE_DIR}/appsw/backup
cd ${BASE_DIR}/appsw

#- 설치 시, 서로 package가 호환되는지 여부를 released 내역을 확인하여 설치 진행  
wget http://archive.apache.org/dist/httpd/httpd-2.4.34.tar.gz
wget https://archive.apache.org/dist/apr/apr-1.6.3.tar.gz
wget https://archive.apache.org/dist/apr/apr-util-1.6.1.tar.gz
wget https://ftp.pcre.org/pub/pcre/pcre-8.42.tar.gz
wget https://archive.apache.org/dist/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.43-src.tar.gz


tar -xzf apr-1.6.3.tar.gz; tar -xzf apr-util-1.6.1.tar.gz; tar -xzf httpd-2.4.34.tar.gz; tar -xzf pcre-8.42.tar.gz; tar -xzf tomcat-connectors-1.2.43-src.tar.gz
mv *.tar.gz ${BASE_DIR}/appsw/backup/
mv ${BASE_DIR}/appsw/apr-1.6.3 ${BASE_DIR}/appsw/httpd-2.4.34
mv ${BASE_DIR}/appsw/apr-util-1.6.1 ${BASE_DIR}/appsw/httpd-2.4.34
mv ${BASE_DIR}/appsw/tomcat-connectors-1.2.43-src ${BASE_DIR}/appsw/httpd-2.4.34
mv ${BASE_DIR}/appsw/pcre-8.42 ${BASE_DIR}/appsw/httpd-2.4.34

 

3. 설치 진행(본작업)

cd ${WEB_DIR}/apr-1.6.3
./configure --prefix=${WEB_DIR}/apr-1.6.3
make clean; make; make install

cd ${WEB_DIR}/apr-util-1.6.1
./configure --prefix=${WEB_DIR}/apr-util-1.6.1 --with-apr=${WEB_DIR}/apr-1.6.3
make clean; make; make install

cd ${WEB_DIR}/pcre-8.42
./configure --prefix=${WEB_DIR}/pcre-8.42
make clean; make; make install

cd ${WEB_DIR}
./configure --prefix=${APP_DIR} --with-apr=${WEB_DIR}/apr-1.6.3 --with-apr-util=${WEB_DIR}/apr-util-1.6.1 --with-pcre=${WEB_DIR}/pcre-8.42 --enable-ssl --with-ssl=/usr/bin/openssl
make clean; make; make install

 

cd ${WEB_DIR}/tomcat-connectors-1.2.43-src/native
./buildconf.sh

vi ${APP_DIR}/bin/apxs

만약, 아래와 같이 perl 이 아닐 시, 수정진행
#!/replace/with/path/to/perl/interpreter -w  =>  #! /usr/bin/perl -w
./configure --with-apxs=${APP_DIR}/bin/apxs
make clean; make; make install

 

설정적용 이어서

.

.

.

 


APACHE Compile 설치방법(WEB/Configuration)

#- 샘플 설정파일들(보안옵션/취약점조치/호스트적용/ETC)

더보기

1. WEB 관련 디렉터리 생성 & 권한부여 & 설정작업(백업 후, 진행)

mkdir -p ${APP_DIR}/logs/jk_log
mkdir -p ${APP_DIR}/logs/error_log
mkdir -p ${APP_DIR}/logs/access_log
mkdir -p ${APP_DIR}/logs/ssl
sudo chown root:apache ${APP_DIR}/bin/httpd
sudo chmod +s ${APP_DIR}/bin/httpd

 

cp ${APP_DIR}/conf/httpd.conf ${APP_DIR}/conf/httpd.conf_`date +%Y%m%d`
cp ${APP_DIR}/conf/extra/httpd-vhosts.conf ${APP_DIR}/conf/extra/httpd-vhosts.conf_`date +%Y%m%d`
cp ${APP_DIR}/conf/extra/httpd-ssl.conf ${APP_DIR}/conf/extra/httpd-ssl.conf_`date +%Y%m%d`

 

vi ${APP_DIR}/conf/httpd.conf

#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/home/apache/apache"

#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:logs

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
Listen 443

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_form_module modules/mod_auth_form.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule allowmethods_module modules/mod_allowmethods.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule cache_socache_module modules/mod_cache_socache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule macro_module modules/mod_macro.so
#LoadModule dbd_module modules/mod_dbd.so
#LoadModule dumpio_module modules/mod_dumpio.so
#LoadModule buffer_module modules/mod_buffer.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
#LoadModule request_module modules/mod_request.so
#LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule deflate_module modules/mod_deflate.so
LoadModule mime_module modules/mod_mime.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
#LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
#LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
#LoadModule remoteip_module modules/mod_remoteip.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so
#LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so
#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so
#LoadModule session_module modules/mod_session.so
#LoadModule session_cookie_module modules/mod_session_cookie.so
#LoadModule session_dbd_module modules/mod_session_dbd.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule ssl_module modules/mod_ssl.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule unixd_module modules/mod_unixd.so
#LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule info_module modules/mod_info.so
#LoadModule cgid_module modules/mod_cgid.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
#LoadModule actions_module modules/mod_actions.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule jk_module modules/mod_jk.so

<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

</IfModule>

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin rord88@daum.net

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride AuthConfig
    #Require all denied
    Require all granted
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/home/apache/apache/htdocs"
<Directory "/home/apache/apache/htdocs">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    #Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride AuthConfig

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html index.jsp index.do
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
#ErrorLog "logs/error_log/error_log"
ErrorLog "|/home/apache/apache/bin/rotatelogs /home/apache/apache/logs/error_log/error.%Y%m%d.log 86400"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b %T \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b %T" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b %T \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log/access_log" common
    SetEnvIf Request_URI "favicon.ico" do_not_log
    CustomLog "|/home/apache/apache/bin/rotatelogs /home/apache/apache/logs/access_log/access.%Y%m%d.log 86400" combined env=!do_not_log


    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    #CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/home/apache/apache/cgi-bin/"

</IfModule>

<IfModule cgid_module>
    #
    # ScriptSock: On threaded servers, designate the path to the UNIX
    # socket used to communicate with the CGI daemon of mod_cgid.
    #
    #Scriptsock cgisock
</IfModule>

#
# "/apache/apache/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/home/apache/apache/cgi-bin">
    AllowOverride AuthConfig
    Options -Indexes -FollowSymLinks -MultiViews -ExecCGI
    Order allow,deny
    Deny from all
    #AllowOverride AuthConfig
    #Options None
    #Require all granted
</Directory>

<IfModule headers_module>
    #
    # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied
    # backend servers which have lingering "httpoxy" defects.
    # 'Proxy' request header is undefined by the IETF, not listed by IANA
    #
    RequestHeader unset Proxy early
</IfModule>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig conf/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    #AddType text/html .shtml
    #AddOutputFilter INCLUDES .shtml
</IfModule>

#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type.  The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
ErrorDocument 400 "/etc/error.html"
ErrorDocument 401 "/etc/error.html"
ErrorDocument 402 "/etc/error.html"
ErrorDocument 403 "/etc/error.html"
ErrorDocument 404 "/etc/error.html"
ErrorDocument 405 "/etc/error.html"
ErrorDocument 500 "/etc/error.html"
ErrorDocument 501 "/etc/error.html"
ErrorDocument 503 "/etc/error.html"

#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
#EnableSendfile on

# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.

# connecting ajp setting (mod_jk)
Include conf/extra/mod_jk.conf

# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf

# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf

# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf

# Language settings
#Include conf/extra/httpd-languages.conf

# User home directories
#Include conf/extra/httpd-userdir.conf

# Real-time info on requests and configuration
#Include conf/extra/httpd-info.conf

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf

# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf

# Various default settings
#Include conf/extra/httpd-default.conf

# Configure mod_proxy_html to understand HTML4/XHTML1
#<IfModule proxy_html_module>
#Include conf/extra/proxy-html.conf
#</IfModule>

# Secure (SSL/TLS) connections
Include conf/extra/httpd-ssl.conf


# Note: The following must must be present to support
#       starting without SSL on platforms with no /dev/random equivalent
#       but a statically compiled-in mod_ssl.
#

<IfModule ssl_module>
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
</IfModule>

<Location /admin>
    Order allow,deny
    Deny from all
</Location>

<Location /admin-console>
    Order allow,deny
    Deny from all
</Location>

<Location /console>
    Order allow,deny
    Deny from all
</Location>

Redirect 404 /favicon.ico
<Location /favicon.ico>
    ErrorDocument 404 "No favicon"
    Deny from all
</Location>

TraceEnable Off
LimitRequestBody 104857600
ServerTokens Prod

<Directory "/home/apache/web">
    AllowOverride AuthConfig
    LimitRequestBody 104857600
    <LimitExcept GET POST>
        Order allow,deny
        Deny from all
    </LimitExcept>
</Directory>
<Directory "/home/apache/web">
    AllowOverride AuthConfig
    LimitRequestBody 104857600
    <LimitExcept GET POST>
        Order allow,deny
        Deny from all
    </LimitExcept>
</Directory>

 

 

vi ${APP_DIR}/conf/extra/httpd-vhosts.conf

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#

#--------------------------
#- host : rord.test.com
#--------------------------
<VirtualHost *:80>
    ServerAdmin rord88@daum.net
    DocumentRoot "/home/apache/web"
    ServerName rord.test.com
    RedirectMatch "^/?(.*)" "https://rord.test.com/$1"
    JKMountFile conf/rord.properties

    <IfModule dir_module>
        DirectoryIndex index.html
    </IfModule>
    <IfModule mod_headers.c>
        Header set Content-Security-Policy: "default-src 'self' data: 'unsafe-inline' 'unsafe-eval' *"
        Header set X-Content-Type-Options: "nosniff"
        Header set X-XSS-Protection: "1; mode=block"
        Header always append X-Frame-Options SAMEORIGIN
        Header always set Strict-Transport-Security "max-age=86400; includeSubDomains; preload"
    </IfModule>
    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{REQUEST_METHOD} !^(GET|POST)
        RewriteRule .* - [R=403,L]
    </IfModule>

    <Directory "/home/apache/web">
        Options -Indexes +FollowSymLinks
        AllowOverride AuthConfig
        LimitRequestBody 104857600
            <LimitExcept GET POST>
                Order deny,allow
                Deny from all
            </LimitExcept>
    </Directory>

    #ProxyPreserveHost On
    #ProxyRequests off
    #ProxyPass "/main" "http://localhost:80/"

    ErrorLog "logs/error_log/rord.test.com-error_log"
    CustomLog "logs/access_log/rord.test.com-access_log" common

</VirtualHost>

 

vi ${APP_DIR}/conf/extra/httpd-ssl.conf

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

SSLProxyCipherSuite HIGH:MEDIUM:!MD5!EXP:!NULL:!LOW:!ADH:!aNULL:!RC4
SSLHonorCipherOrder on
#SSLPassPhraseDialog  builtin
SSLPassPhraseDialog exec:/home/apache/apache/ssl_private/ssl_pwd.sh
SSLSessionCache        "shmcb:/home/apache/apache/logs/ssl_scache(512000)"
SSLSessionCacheTimeout  300
SSLUseStapling On
SSLStaplingResponderTimeout 5
SSLStaplingReturnResponderErrors off
SSLStaplingCache "shmcb:/home/apache/apache/logs/ssl_stapling(128000)"
SSLStaplingStandardCacheTimeout 3600
SSLStaplingErrorCacheTimeout 600

##
## SSL Virtual Host Context
##
SetEnvIf Request_URI "favicon.ico" do_not_log
LogFormat "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b %T \"%{Referer}i\" \"%{User-Agent}i\"" ssl_common

#--------------------------
#- host : rord.test.com
#--------------------------
<VirtualHost *:443>
    ServerAdmin rord88@daum.net
    DocumentRoot "/home/apache/web"
    ServerName rord.test.com
    JKMountFile conf/rord.properties
    # enable HTTP/2, if available
    Protocols h2 http/1.1

    <IfModule mod_headers.c>
        Header set Content-Security-Policy: "default-src 'self' data: 'unsafe-inline' 'unsafe-eval' *"
        Header set X-Content-Type-Options: "nosniff"
        Header set X-XSS-Protection: "1; mode=block"
        Header always append X-Frame-Options SAMEORIGIN
        Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
    </IfModule>
    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{REQUEST_METHOD} !^(GET|POST)
        RewriteRule .* - [R=403,L]
    </IfModule>

    <Directory "/home/apache/web">
        Options -Indexes +FollowSymLinks
        AllowOverride AuthConfig
        LimitRequestBody 104857600
            <LimitExcept GET POST>
                Order deny,allow
                Deny from all
            </LimitExcept>
    </Directory>
    <IfModule dir_module>
        DirectoryIndex index.html session.jsp
    </IfModule>

    #ProxyPreserveHost On
    #ProxyRequests off
    #ProxyPass /main https://localhost:443/

    TransferLog "logs/ssl/rord.test.com-ssl-access_log"
    ErrorLog "logs/ssl/rord.test.com-ssl-error_log"

    SSLEngine on
    SSLProtocol all -SSLv2 -SSLv3
    SSLCipherSuite          ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS
    SSLHonorCipherOrder Off
    SSLCompression          off
    SSLSessionTickets       off

    SSLCertificateFile "/home/apache/apache/ssl_private/certs/rord_test_com.crt"
    SSLCertificateKeyFile "/home/apache/apache/ssl_private/certs/rord_test_com.key"
    #SSLCertificateChainFile "/home/apache/apache/ssl_private/certs/ChainCA.crt"

    <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory "/apache/apache24/cgi-bin">
        SSLOptions +StdEnvVars
    </Directory>

    BrowserMatch "MSIE [2-5]" \
    nokeepalive ssl-unclean-shutdown \
    downgrade-1.0 force-response-1.0
    
</VirtualHost>

  

vi ${APP_DIR}/conf/extra/mod_jk.conf

# mod_jk.conf
#
# Required modules: mod_jk.so
# You may use the command line Configuration.
#
#

<IfModule jk_module>
#<IfModule mod_jk.c>
    # Add the module (activate this lne for Apache 1.3)
    # AddModule     mod_jk.c
    # Where to find workers.properties
    JkWorkersFile conf/workers.properties
    # Where to put jk shared memory
    JkShmFile     logs/mod_jk.shm
    # Where to put jk logs
    #JkLogFile     logs/jk_log/mod_jk.log
    JkLogFile     "|/home/apache/apache/bin/rotatelogs /home/apache/apache/logs/jk_log/mod_jk.log 86400"
    # Set the jk log level [debug/error/info]
    JkLogLevel    info
    # Set the jk log format
    #JKLogStampFormat "[%a %b %d %H:%M:%S %Y]"
    JkLogStampFormat "[%y-%m-%d %H:%M:%S.%Q] "
    #URI pattern Setting Files
    #JKMountFile conf/uriworkermap.properties
</IfModule>

 

vi ${APP_DIR}/conf/workers.properties

# The advanced router LB worker
worker.list=rordlb,jkstatus

worker.rordlb.type=lb
worker.rordlb.retries=2
worker.rordlb.method=Session
worker.rordlb.sticky_session=true
worker.rordlb.balance_workers=rord11,rord12

# Define a 'jkstatus' worker using status
worker.jkstatus.type=status

# Define the Template worker setting
worker.template.type=ajp13
worker.template.lbfactor=1
worker.template.socket_timeout=300
worker.template.socket_keepalive=true
#worker.template.connect_timeout=30000
worker.template.recovery_options=7
worker.template.ping_mode=A
worker.template.ping_timeout=10000
worker.template.connection_pool_size=500
worker.template.connection_pool_minsize=300
worker.template.connection_pool_timeout=60

# Define the first member worker
worker.rord11.reference=worker.template
worker.rord11.host=172.31.43.101
worker.rord11.port=9109
worker.rord11.route=rord11

# Define the second member worker
worker.rord12.reference=worker.template
worker.rord12.host=172.31.43.101
worker.rord12.port=9209
worker.rord12.route=rord12

 

vi ${APP_DIR}/conf/rord.properties

## Mapping the ALL URI
/*.jsp=rordlb
/*.do=rordlb
/*.json=rordlb
/*.xmldo=rordlb
/*.htmdo=rordlb
/*.action=rordlb
/*.pop=rordlb
/*.ifrm=rordlb

 

cp ${APP_DIR}/htdocs/index.html ${AP_DIR}/

 

#- 브라우저 PC 호스트 설정

C:\Windows\System32\drivers\etc\hosts
15.164.166.70 rord.test.com

 

C:\Windows\System32\drivers\etc\hosts 내, 서버ip & DNS 정보 저장

 

설정적용 이어서

.

.

.

 


APACHE Compile 설치방법(WEB/SSL Self-Signed-Cert Generate)

더보기

1. SSL Self-Signed-Certifcation 디렉터리 생성 & 스크립트 작성

mkdir -p ${BASE_DIR}/scripts/createSignCert

cd ${BASE_DIR}/scripts/createSignCert

 

vi ${BASE_DIR}/scripts/createSignCert/generateSignCert.sh

base_dir=`pwd`
web_cert_dir=${APP_DIR}/ssl_private/certs
openssl genrsa -aes256 -out ${base_dir}/RootCA.key 2048
chmod 600  ${base_dir}/RootCA.key

#- RootCA
openssl req -new -key ${base_dir}/RootCA.key -out ${base_dir}/RootCA.csr -config ${base_dir}/rootca_openssl.conf

openssl x509 -req -days 365 -extensions v3_ca -set_serial 1 \
-in ${base_dir}/RootCA.csr -signkey ${base_dir}/RootCA.key \
-out ${base_dir}/RootCA.crt -extfile ${base_dir}/rootca_openssl.conf

openssl x509 -text -in ${base_dir}/RootCA.crt

#- rord_test_com
openssl genrsa -aes256 -out ${base_dir}/rord_test_com.key 2048

cp ${base_dir}/rord_test_com.key ${base_dir}/rord_test_com.key.enc
openssl rsa -in ${base_dir}/rord_test_com.key.enc -out  ${base_dir}/rord_test_com.key

chmod 600 ${base_dir}/rord_test_com.key*


openssl req -new -key ${base_dir}/rord_test_com.key -out ${base_dir}/rord_test_com.csr -config ${base_dir}/host_openssl.conf

openssl x509 -req -days 365 -extensions v3_user -in ${base_dir}/rord_test_com.csr \
-CA ${base_dir}/RootCA.crt -CAcreateserial \
-CAkey  ${base_dir}/RootCA.key \
-out ${base_dir}/rord_test_com.crt  -extfile host_openssl.conf

openssl x509 -text -in ${base_dir}/rord_test_com.crt

if [ ! -d ${web_cert_dir} ]; then
    mkdir -p ${web_cert_dir}
fi

cp rord_test_com.crt ${web_cert_dir}/
cp rord_test_com.key ${web_cert_dir}/
ls -lrt ${web_cert_dir}/

 

vi ${BASE_DIR}/scripts/createSignCert/host_openssl.conf

#-------------------------------------------------------------------------------------
#- 파라메터를 default 값으로 정의하여 인증서 생성시 간략화 가능(사용자 정보로 재정의하여사용)
#-------------------------------------------------------------------------------------
[ req ]
default_bits            = 2048
default_md              = sha256
default_keyfile         = RootCA.key
distinguished_name      = req_distinguished_name
extensions             = v3_user

[ v3_user ]
basicConstraints = CA:FALSE
authorityKeyIdentifier = keyid,issuer
subjectKeyIdentifier = hash
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth,clientAuth
subjectAltName          = @alt_names

[ alt_names]
DNS.1   = rord.test.com
DNS.2   = *.test.com

[req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = KR
countryName_min                 = 2
countryName_max                 = 2


organizationName              = Organization Name (eg, company)
organizationName_default      = rord Inc.

organizationalUnitName          = Organizational Unit Name (eg, section)
organizationalUnitName_default  = rord Team

commonName                      = Common Name (eg, your name or your server's hostname)
commonName_default             = rord Self Signed CA
commonName_max                  = 64
#-------------------------------------------------------------------------------------

 

vi ${BASE_DIR}/scripts/createSignCert/rootca_openssl.conf

#-------------------------------------------------------------------------------------
#- 파라메터를 default 값으로 정의하여 인증서 생성시 간략화 가능(사용자 정보로 재정의하여사용)
#-------------------------------------------------------------------------------------

[ req ]
default_bits            = 2048
default_md              = sha256
default_keyfile         = RootCA.key
distinguished_name      = req_distinguished_name
extensions             = v3_ca
req_extensions = v3_ca

[ v3_ca ]
basicConstraints       = critical, CA:TRUE, pathlen:0
subjectKeyIdentifier   = hash
##authorityKeyIdentifier = keyid:always, issuer:always
keyUsage               = keyCertSign, cRLSign
nsCertType             = sslCA, emailCA, objCA
[req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = KR
countryName_min                 = 2
countryName_max                 = 2

organizationName              = Organization Name (eg, company)
organizationName_default      = rord Inc.

organizationalUnitName          = Organizational Unit Name (eg, section)
organizationalUnitName_default  = rord Team

commonName                      = Common Name (eg, your name or your server's hostname)
commonName_default             = rord Self Signed CA
commonName_max                  = 64
#----------------------------------------------------------------------------------------

 

vi ${APP_DIR}/ssl_private/ssl_pwd.sh

#!/bin/sh
case "$1" in
    "rord.test.com:443")
    #-패스워드는 발급 또는 생성한 값으로 대체
    echo "apache1234!"
    ;;
esac

 

2. 스크립트 실행(SSL Self-Signed-Certifcation 생성)

sh ${BASE_DIR}/scripts/createSignCert/generateSignCert.sh
스크립트를 실행하면 RootCa인증서 생성 단계부터 차례대로 생성되며, 중간에 key 값의 패스워드를 넣어주며 진행(잊어먹지말자)

 

서버/클라이언트 인증서 생성 단계도 마찬가지로 인증서 생성시 패스워드 입력란이 존재한다.(패스워드를 잊어먹지말자)

 


APACHE Compile 설치방법(WEB/Operation & Check)

더보기

 

설정 완료 후, APACHE WEB기동 & CHECK

 

hosts 등록한 url 접속 및 정상확인

 

접속여부 로그확인

 


APACHE 속도개선 방안(WEB/mod_deflate & gzip expression)

더보기

1. WEB 영역 속도개선을 위한 최적화 방안

최적화를 위해 front에 위치한 WEB영역에서 APP의 경량화 또는 WAS영역 서비스로직 단축 등 여러 기안이 있음.

1. mod_deflate
2. gzip expression
위 기안은 gzip을 이용한 LZ77알고리즘 기반의 web서버설정이며, 선/후 압축의 차이.

 

[mod_deflate]
http compression 기술로 분류 되어 있으며, client와 server간의 통신을 이용하여 사용자 브라우저에서 gzip압축/해제지원 여부를 확인 후, web서버에서 사용자로부터 호출된 자원을 gzip으로 자동 압축하여 사용자에게 전송시킴. 이점으로 전송하는 사이즈가 작아지는 만큼 속도가 빨라지나, 단점으로 압축률설정에 따른 서버cpu사용률이 증가 할 수 있다는 점.

 

mod_deflate를 사용하기 위해서는 DSO(Dynamic Shared Object)를 web(apache) httpd.conf에 등록필요.

 

#- so가 없을 시, apsx를 이용하여 recompile(자동추가)

${APP_DIR}/bin/apxs -cia -Wl,"-lz" ${WEB_DIR}/modules/filters/mod_deflate.c

#recompile 후, compile check
${APP_DIR}/bin/httpd -l mod_deflate.c

 

보다 상세 설정 정보는 하단의  References의 (아파치_DOCS)mod_defalte를 참조.

- 비슷한모듈정보 : mod_gzip

 

[gzip expression]
특정 확장자 대상을 기준으로 모아 사전에 gzip압축하여 배포하면 되나,
이미 상용중인 서버라면 자원의 압축 대상 분별 및 영향도 분석필요.

(ex: jsp의 js와 css의존성에 따른 소스 수정필요)


예) css.gz 호출 시, 강제로 mime.type에 맞게 형변환 설정

Options + MultiViews
RemoveType .gz
AddEncoding gzip .gz

RemoveEncoding .gz
ForceType application/javascript


RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -f
RewriteRule ^(.*)\.css $1\css\.gz [QSA]

# Server correct content types, and prevent
mod_deflate double gzip
RewriteRule css.gz$ - [T=text/css,E=no-gzip:1]

 

※두 모듈을 같이 응용한다면 좀더 나은 설정이 가능.

 

#- References

(아파치)공식홈페이지

(아파치)아카이브

(pcre)공식홈페이지

(pcre)아카이브

(아파치)DOCS

(WEB/Mozilla)HEADER정보

(IIS)Generate Self-Signed-Certifcation

(IBM)Generate Self-Signed-Certifcation

(SSL)Generate Self-Signed-Certifcation

(IBM) List of control key assignments for your terminal (stty command)

(Manual)Sudoers

(아파치_DOCS)mod_defalte

(wiki)http_compression

Self-Signed-Cert-Trust-Manager(InstallCert.java)

(WEB/Mozilla) ssl-config

'인프라 > MW' 카테고리의 다른 글

[GitLab/Linux or Unix] password reset (Root/Admin)  (0) 2019.12.20
(Keystore)Self-Signed-Cert-Trust-Manager(InstallCert.java)  (0) 2019.10.16
SVN(Subversion)  (0) 2019.09.26
Nginx  (0) 2019.09.26
Jenkins  (0) 2019.09.25