1. apache2.2 設定

最後更新: 2019-03-15

目錄

  • Server configuration
  • Apache MPM prefork
  • graceful
  • KeepAlive
  • log
  • https
  • _default_
  • vhosts
  • Line Breaks in Apache httpd Configuration Directives
  • Troubleshoot

 


Server configuration

 

# Ensure that Apache listens on port 80
Listen 80

# Listen for virtual host requests on all IP addresses
NameVirtualHost *:80

<VirtualHost *:80>
  DocumentRoot /home/vhosts/example.com/public_html
  ServerName example.com

  # ServerAlias 可以用幾次及 wildcards "*"
  ServerAlias www.example.com
  ServerAlias example.net *.example.net

  DirectoryIndex index.php index.htm

  # 目錄
  <Directory /home/vhosts/example.com/public_html>
    Options +Indexes
    # AllowOverride All|None|directive-type [directive-type]   
    AllowOverride All
  </Directory>

</VirtualHost>

########################## 另一個 vhost ######################
<VirtualHost *:80>
  DocumentRoot /www/example2
  ServerName example.org
  ServerAlias *.example.com

  # Other directives here

</VirtualHost>

 


Apache MPM prefork

 

介紹

MPMs 全名叫 Multi-Processing Modules, 一共有3種. 分別是 prefork(Default), worker 及 event

不同之處在於 worker 是行 thread 的.

設定:

# MaxSpareServers: Maximum number of idle child server processes
# If there are more than MaxSpareServers idle, then the parent process will kill off the excess processes.

# After MaxRequestsPerChild requests, the child process will die.

<IfModule prefork.c>
StartServers      20
MinSpareServers    5
MaxSpareServers   20
ServerLimit      256
MaxClients       256
MaxRequestsPerChild  4000
</IfModule>

MaxClients 與 ServerLimit

# MaxClients:

Maximum number of connections that will be processed simultaneously

Any connection attempts over the MaxClients limit will normally be queued

Once a child process is freed at the end of a different request, the connection will then be serviced.

# ServerLimit :

For the prefork MPM, this directive sets the maximum configured value for MaxClients for the lifetime of the Apache process.

Any attempts to change this directive during a reload will be ignored, but MaxClients can be modified during a reload.

Do not set the value of this directive any higher than what you might want to set MaxClients to.

There is a hard limit of ServerLimit 20000 compiled into the server

 * 即使 MaxClients > ServerLimit 那最後的 process 上限都會係 ServerLimit

# ListenBacklog:

Default: 511

Maximum length of the queue of pending connections

 


ServerLimit number

 

For the prefork MPM, this directive sets the maximum configured value for MaxClients for the lifetime of the Apache process.

Any attempts to change this directive during a restart will be ignored, but MaxClients can be modified during a restart.

There is a hard limit of ServerLimit 20000 compiled into the server. This is intended to avoid nasty effects caused by typos.

 


graceful

 

apache 重讀大部份 configure

service httpd graceful

在系統會見到

 9413 ?        00:10:49 httpd
 9543 ?        00:00:14 httpd <defunct>
14628 ?        00:00:09 httpd <defunct>
14760 ?        00:00:11 httpd <defunct>
14761 ?        00:00:13 httpd <defunct>
14762 ?        00:00:13 httpd <defunct>
14763 ?        00:00:47 httpd <defunct>

* vhost 是有更新的
* graceful 後, 不用再入 SSL 的 Key Password

 


KeepAlive

 

Global Setting (/etc/apache2/apache2.conf)

KeepAlive off
MaxKeepAliveRequests 50
KeepAliveTimeout 5

# 在個別 vhost 上啟用 KeepAlive

<VirtualHost *:80>
    KeepAlive On
    ...
</VirtualHost>

When a client uses a Keep-Alive connection, it will be counted as a single "request" for the MaxConnectionsPerChild directive

(regardless of how many requests are sent using the connection)

HTTP Headers

 

Request header: Connection: keep-alive

Response Header: Connection: keep-alive

Connection Timeout

在 KeepAliveTimeout 內收到 Package 後就開始計 Timeout

# Timeout: The number of seconds before receives and sends time out.
Timeout 8

 


Centos test page

 

log

Directory index forbidden by Options directive: /home/vhosts/domain/public_html/

原因有以下設定存在 /etc/httpd/conf.d/welcome.conf

#
# This configuration file enables the default "Welcome"
# page if there is no default index page present for
# the root URL.  To disable the Welcome page, comment
# out all the lines below.
#
<LocationMatch "^/+$">
    Options -Indexes
    ErrorDocument 403 /error/noindex.html
</LocationMatch>

 


Log

 

什麼都不 log

CustomLog "/dev/null" combined
ErrorLog "/dev/null"

log 去某 file

CustomLog "/home/vhosts/xxx/logs/access.log" combined
ErrorLog "/home/vhosts/xxx/logs/error.log"

log level

LogLevel warn

用 rotatelogs

ErrorLog "| /usr/sbin/rotatelogs -f -l /var/log/apache2/datahunter.org/error.log.%Y.%m.%d 86400"
Customlog "| /usr/sbin/rotatelogs -f -l /var/log/apache2/datahunter.org/access.log.%Y.%m.%d 5M" combined

LogFormat

LogFormat  "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\""  vhost_combined
LogFormat  "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\""  combined
LogFormat  "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x %r %b"  httpslog

CustomLog  "/home/vhosts/datahunter.org/logs/ssl_access_log"  httpslog

commonly used log format strings

common

"%h %l %u %t \"%r\" %>s %b"

combined

"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""

s.s.s.s - - [12/Mar/2019:10:23:34 +0800] "GET /URL HTTP/1.1" 200 2185 "???" "Mozilla/5.0 ...."

 

%s     Status.

For requests that have been internally redirected, this is the status of the original request. Use %>s for the final status.

%b     

Size of response in bytes, excluding HTTP headers. In CLF format, i.e. a '-' rather than a 0 when no bytes are sent.

%I     

Bytes received, including request and headers. Cannot be zero. You need to enable mod_logio to use this.

%{VARNAME}C     

The contents of cookie VARNAME in the request sent to the server.

%{VARNAME}i     

The contents of VARNAME: header line(s) in the request sent to the server.

%D     The time taken to serve the request, in microseconds.

%T     The time taken to serve the request, in seconds.

%k     Number of keepalive requests handled on this connection.

'1' means the first keepalive request after the initial one

'0'  indicating the initial request

%P     The process ID of the child that serviced the request.

%X     Connection status when response is completed:

X      # Connection aborted before the response completed.

+      #Connection may be kept alive after the response is sent.

-       # Connection will be closed after the response is sent.

i.e.

# 保留原本的 log

CustomLog "logs/access.log" combined

# MyLogFormat

LogFormat "%h %t \"%r\" %>s %b \"%{User-agent}i\" DEBUG: P:%P K:%k S:%X R:%D C:%{PHPSESSID}C" MyLogFormat
CustomLog "logs/MyLogFormat.log" MyLogFormat

 

 


https

 

Error:

_default_ VirtualHost overlap on port 443, the first has precedence

加入 setting

<IfModule mod_ssl.c>
    NameVirtualHost *:443
    Listen 443
</IfModule>

 


ErrorDocument

 

ErrorDocument error-code document

a slash (/) for local web-paths (relative to the DocumentRoot)

example:

ErrorDocument 500 http://foo.example.com/cgi-bin/tester
ErrorDocument 401 /subscription_info.html
ErrorDocument 403 "Sorry can't allow you access today"

 


_default_

 

The string _default_, which is used only with IP virtual hosting to catch unmatched IP addresses.

# 以下兩個設定可以同時存在, 不過一定要注意順序

# _default_ vhosts for one port
<VirtualHost _default_:80>
    # ...
</VirtualHost>

# _default_ vhosts for all ports
<VirtualHost _default_:*>
    # ...
</VirtualHost>

NameVirtualHost 的 default

Apache uses the first block if no other matching block is found

以下兩個設定都係癈的

  • "ServerAlias *"
  • "not setting a ServerName"

 

 


Other

AddHandler php5-script .php

AddType text/html .php

AddDefaultCharset utf-8

 

 


Virtual host

 

Name-based virtual host (用 "ServerName")

the server relies on the client to report the hostname as part of the HTTP headers.

ports.conf

# The use of <VirtualHost> does not affect what addresses Apache listens on.
# You may need to ensure that Apache is listening on the correct addresses using Listen.
Listen 80

vhosts.conf

NameVirtualHost *

# The character *, which is used only in combination with NameVirtualHost * to match all IP addresses;
<VirtualHost *:80>
    DocumentRoot /home/vhosts/datahunter.org/public_html

    # If it is absent, the ServerName from the "main" server configuration will be inherited.
    ServerName datahunter.org
 
    # Other directives here
</VirtualHost>

IP-based virtual host

Listen 192.168.0.1:80
Listen 192.168.0.1:80

<VirtualHost 192.168.0.1:80>
  ServerAdmin datahunter.org@datahunter.org
  DocumentRoot /home/vhosts/datahunter.org/public_html

  ErrorLog    /home/vhosts/datahunter.org/logs/error_log
  TransferLog /home/vhosts/datahunter.org/logs/access_log

  # Other directives here
</VirtualHost>

<VirtualHost 192.168.0.2:80>
  ServerAdmin datahunter.org@datahunter.org
  DocumentRoot /home/vhosts/tools.datahunter.org/public_html

  # Other directives here
</VirtualHost>

Catching every request to any unspecified IP address and port

<VirtualHost _default_:*>
    DocumentRoot /var/www/default
</VirtualHost>

In the absence of any _default_ virtual host the "main" server config,

consisting of all those definitions outside any VirtualHost section, is used when no IP-match occurs.

Note

that any IP address that matches a NameVirtualHost directive will use

neither the "main" server config nor the _default_ virtual host.

OverAll

NameVirtualHost *:80

################################################### must first vhost
<VirtualHost *:80>
  ServerName IP
  DocumentRoot /home/vhosts/IP/public_html
  ErrorLog /dev/null
  CustomLog /dev/null combined
  <Directory /home/vhosts/IP/public_html>
      AllowOverride All
      Options Includes ExecCGI FollowSymLinks
  </Directory>
  IndexOptions FancyIndexing
</VirtualHost>

################################################### datahunter.org
<VirtualHost *:80>
    ServerName datahunter.org
    ServerAlias www.datahunter.org
    DocumentRoot /home/vhosts/datahunter.org/public_html

    ErrorLog "/home/vhosts/datahunter.org/logs/error.log"
    CustomLog "/home/vhosts/datahunter.org/logs/access.log" combined

    <Directory /home/vhosts/datahunter.org/public_html>
        Options -Indexes +ExecCGI -FollowSymLinks
        AllowOverride All
    </Directory>
    IndexOptions FancyIndexing
</VirtualHost>

 


Line Breaks in Apache httpd Configuration Directives

 

Just use the backslash (\)

i.e.

ProxyPass http://backend.example.com/a-long-path-to-demonstrate \
    connectiontimeout=1 retry=0

 


Troubleshoot

 

Error Log 1:

[Wed May 04 15:58:36 2016] [notice] child pid 4941 exit signal File size limit exceeded (25)

原因

1. log file over size (2G)
2. php open file over 2G

find . -size +2000000