1. Apache2.2 設定

最後更新: 2024-02-09

目錄

 


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, Apache 一共有 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

Apache httpd will wait for I/O in various circumstances. Default 60

Timeout 60
  • When reading data from the client, the length of time to wait for a TCP packet to arrive if the read buffer is empty.
  • When writing data to the client, the length of time to wait for an acknowledgement of a packet if the send buffer is full.
  • In mod_cgi and mod_cgid, the length of time to wait for any individual block of output from a CGI script.
  • In mod_ext_filter, the length of time to wait for output from a filtering process.
  • In mod_proxy, the default timeout value if ProxyTimeout is not configured.

 


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

 

Syntax

ErrorDocument <3-digit-code> <action>

Action

  • A slash (/) for local web-paths (relative to the DocumentRoot)
  • Wrap the text with quotes (") - Text to be displayed
  • An external URL to redirect to.

Digit-Code

  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found

ie.

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 [email protected]
  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 [email protected]
  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

 


DNS Lookup

 

HostnameLookups Off

 


SetHandler

 

A "handler" is an internal Apache representation of the action to be performed when a file is called.

"SetHandler" Forces all matching files to be processed by a handler.

Syntax: SetHandler handler-name|none|expression

 * When placed into an .htaccess file or a <Directory> or <Location> section,
      this directive forces all matching files to be parsed through the handler given by handler-name.

 * You can override an earlier defined SetHandler directive by using the value None.

e.g.

[1] handler-name

<Location "/status">
  SetHandler server-status
</Location>

[2] handler-name

<FilesMatch "\.php$">
    SetHandler application/x-httpd-php
</FilesMatch>

* application/x-httpd-php is not a MIME type, but rather a handler.

[3] expressions

# php80-php-fpm
<FilesMatch ".+\.php$">
    SetHandler application/x-httpd-php
    SetHandler "proxy:fcgi://127.0.0.1:9080"
</FilesMatch>

 

AddHandler

Maps the filename extensions to the specified handler

Syntax: AddHandler handler-name extension [extension] ...

 * The extension argument is case-insensitive

e.g.

AddHandler cgi-script .cgi

 

 


Options

 

功能

Configures what features are available in a particular directory

Syntax

Options [+|-]option [[+|-]option] ...

If multiple Options could apply to a directory, then the most specific one is used and others are ignored; the options are not merged.

However if all the options on the Options directive are preceded by a + or - symbol, the options are merged.

當有選項用了 +/- 時, 那其餘的都要加 +/- (All 除外)

Options

None

none of the extra features are enabled

All

All options except for MultiViews

FollowSymLinks

The server will follow symbolic links in this directory. This is the default setting.

 * The default in the absence of any other settings is FollowSymlinks.

 * Even though the server follows the symlink it does not change the pathname used to match against <Directory> sections.

SymLinksIfOwnerMatch

The server will only follow symbolic links for which the target file or directory is owned by the same user id as the link.

啟用 mod_X 的功能

Includes (mod_include)

Server-side includes provided by mod_include are permitted.

IncludesNOEXEC (mod_include)

Server-side includes are permitted, but the #exec cmd and #exec cgi are disabled.

ExecCGI (mod_cgi)

Execution of CGI scripts using mod_cgi is permitted.

Indexes (mod_autoindex)

If a URL which maps to a directory is requested and there is no DirectoryIndex (e.g., index.html) in that directory,
then mod_autoindex will return a formatted listing of the directory.

MultiViews (mod_negotiation)

Content negotiated "MultiViews" are allowed using mod_negotiation.

Example

1) Disable Directory Listing

Using <Directory ...>

<Directory /{YOUR DIRECTORY}>
  Options -Indexes +FollowSymLinks
  # 或者
  #Options FollowSymLinks
</Directory>

Using .htaccess

Options -Indexes

 


Config Merged

 

The order of merging is:

  1. <Directory> (except regular expressions) and .htaccess done simultaneously
    (with .htaccess, if allowed, overriding <Directory>)
  2. <DirectoryMatch> (and <Directory "~">)
  3. <Files> and <FilesMatch> done simultaneously
  4. <Location> and <LocationMatch> done simultaneously
  5. <If> sections, even when they are enclosed in any of the preceding contexts.

 

Example 1

.env, .gitignore, .git 它們會 "Forbidden"

.htaccess

<FilesMatch "^\.">
        Require all denied
</FilesMatch>

Require all granted

Example 2

Result: three

<Directory "/">
    Header set CustomHeaderName one
    <FilesMatch ".*">
        Header set CustomHeaderName three
    </FilesMatch>
</Directory>

<Directory "/example">
    Header set CustomHeaderName two
</Directory>

Example 3

次序: A(First) > B > C > D > E (Last)

 * Last Win

<Location "/">
    E
</Location>

<Files "f.html">
    D
</Files>

<VirtualHost *>
    <Directory "/a/">
        B
    </Directory>
</VirtualHost>

<DirectoryMatch "^.*b$">
    C
</DirectoryMatch>

<Directory "/a/b">
    A
</Directory>

Notes

  • <Directory> is processed in the order shortest directory component to longest.
    For example, <Directory "/var/web/dir"> will be processed before <Directory "/var/web/dir/subdir">.
  • If multiple <Directory> sections apply to the same directory they are processed in the configuration file order.
  • Sections inside <VirtualHost> sections are applied after the corresponding sections outside the virtual host definition.

 


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

 


 

 

 

 

 

Creative Commons license icon Creative Commons license icon