LPIC201/202 あずき本 ch10 Webサーバとプロキシサーバ (1/3)

ApacheLPIC202勉強メモ資格勉強

出典: 

10.1 Webサーバの設定

Apache HTTP Server の話

Column: MPM

MPM: Multi Processing Module という基本モジュールによって動作が異なる

prefork worker perchild event
reqに対して子プロセス数をスケール o o x o
reqに対して子プロセスのスレッド数をスケール - o o o
  • eventはworkerと似ている、keep aliveの処理が異なる
  • MPMによって動作しないソフトウェアもある

    • PHPはprefork前提
    • 【所感】「PHPは1リクエスト1プロセス」というのはこれのことかな

10.1.1 Apacheのインストール

  • Red Hat系: httpd
  • Debian系: apache2
sudo yum -y install httpd

10.1.2 Apacheの設定

  • ソースからインストールすると/usr/local/apache2/conf/httpd.conf

    • dockerのhttpd:2.4イメージなんかはこれ
  • Red Hat系: /etc/httpd/conf/httpd.conf
  • Debian系: /etc/apache2/apache2.conf

debian系だとコンフィグの分割ヒエラルキーを教えてくれてる 優しい

sudo cat /etc/apache2/apache2.conf
...
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#	/etc/apache2/
#	|-- apache2.conf
#	|	`--  ports.conf
#	|-- mods-enabled
#	|	|-- *.load
#	|	`-- *.conf
#	|-- conf-enabled
#	|	`-- *.conf
# 	`-- sites-enabled
#	 	`-- *.conf
#
...

CentOS7のコンフィグ実例

sudo cat /etc/httpd/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 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/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 "/etc/httpd"

#
# 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

#
# 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
#
Include conf.modules.d/*.conf

#
# 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

# '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 root@localhost

#
# 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 www.example.com:80

#
# 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 none
    Require all denied
</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 "/var/www/html"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # 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:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # 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
</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"

#
# 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 \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{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" common

    #
    # 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/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/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>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the 
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # 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
</IfModule>

#
# 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
#

#
# 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 if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

この部分

IncludeOptional conf.d/*.conf

機能ごとに複数の設定ファイル/etc/httpd/conf.d/*.confに分割してインクルードするのが普通

ディレクティブ

ディレクティブ: httpd.confの各種設定項目

...
#
# 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 "/var/www/html"
...

ディレクティブの適用範囲を指定することもできる

  • ファイル
  • ディレクトリ
  • URL
#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ".ht*">
    Require all denied
</Files>
#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>
cat /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. 
#
# NOTE: if this file is removed, it will be restored on upgrades.
#
<LocationMatch "^/+$">
    Options -Indexes
    ErrorDocument 403 /.noindex.html
</LocationMatch>
...

10.1.3 httpd.confの主な設定

ServerTokens

HTTPヘッダ内に出力されるバージョン情報(バナー情報)指定

curl -v localhost > /dev/null
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* About to connect() to localhost port 80 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost
> Accept: */*
> 
< HTTP/1.1 403 Forbidden
< Date: Thu, 31 Dec 2020 05:57:07 GMT
< Server: Apache/2.4.6 (CentOS)
< Last-Modified: Thu, 16 Oct 2014 13:20:58 GMT
< ETag: "1321-5058a1e728280"
< Accept-Ranges: bytes
< Content-Length: 4897
< Content-Type: text/html; charset=UTF-8
< 
{ [data not shown]
100  4897  100  4897    0     0   713k      0 --:--:-- --:--:-- --:--:--  797k
* Connection #0 to host localhost left intact

この部分:

< Server: Apache/2.4.6 (CentOS)

攻撃の糸口になるので隠すが吉

# vi /etc/httpd/conf/httpd.conf
...
+ ServerTokens Prod
...
curl -v localhost > /dev/null
...
< Server: Apache
...

ServerRoot

#
# 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 "/etc/httpd"

httpdが使用するトップディレクトリ

ServerName

#
# 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 www.example.com:80

サーバのホスト名か、IPアドレスを指定する

hostname -d
asia-northeast1-b.c.lpic2-study.internal

これを指定するのかな多分

ServerAdmin

#
# 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 root@localhost

エラーページ等に表示されるサーバ管理者連絡先メールアドレス

プロセス数の設定

  • StartServers

    • 起動時子プロセス数
  • MinSpareServers

    • 待機子プロセス最小数
  • MaxSpareServers

    • 待機子プロセス最小数
  • ServerLimits

    • 子プロセス最大数

同時接続数

  • MaxClients

    • <=2.2(本当は<=2.3.13)
  • MaxRequestWorkers

    • 2.4<=

Timeout

クライアントからの接続がタイムアウトになる時間(秒数)

キープアライブ

https://tools.ietf.org/html/rfc7230#appendix-A.1.2

HTTP/1.0では、1リクエスト/レスポンスごとにTCPコネクションを確立・切断する

HTTP/1.1で、リクエスト/レスポンスをまたいでTCPコネクションを維持できるようになった — Keep-Alive

良し悪し

  • 1ページビューあたりのTCPコネクションが減る可能性がある

    • ただし、きょうびHTTP自体が6並列くらいで走るので思うように減らないこともある
  • サーバーが同時に抱えるコネクション数は増える

    • コネクションプールやサーバリソースの枯渇等、考えることが増える

きょうびはGoogleのSPDYプロトコルや、その標準化のHTTP/2により役目を終えた

https://www.nic.ad.jp/ja/newsletter/No68/0800.html


  • KeepAlive on|off
  • MaxKeepAliveRequests 上限リクエスト数
  • KeepAliveTimeout タイムアウト時間

Listen

#
# 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

v6の場合は

Listen [::1]:80

のように[]で囲む (IPv6自体の仕様)

User/Group

httpd子プロセスの実行ユーザ/グループ指定

#
# 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

apacheインストール時に一般ユーザ/グループapacheができている

grep apache /etc/passwd
grep apache /etc/group
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
apache:x:48:

apachenobodyを指定

DocumentRoot

#
# 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 "/var/www/html"

UserDir

mkdir ~wand/public_html/
echo hoge > ~wand/public_html/index.html

http://localhost/~wand/~wand/public_html/index.html にアクセスできるようにする

cat /etc/httpd/conf.d/userdir.conf
#
# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received.
#
# The path to the end user account 'public_html' directory must be
# accessible to the webserver userid.  This usually means that ~userid
# must have permissions of 711, ~userid/public_html must have permissions
# of 755, and documents contained therein must be world-readable.
# Otherwise, the client will only receive a "403 Forbidden" message.
#
<IfModule mod_userdir.c>
    #
    # UserDir is disabled by default since it can confirm the presence
    # of a username on the system (depending on home directory
    # permissions).
    #
    UserDir disabled

    #
    # To enable requests to /~user/ to serve the user's public_html
    # directory, remove the "UserDir disabled" line above, and uncomment
    # the following line instead:
    # 
    #UserDir public_html
</IfModule>

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory "/home/*/public_html">
    AllowOverride FileInfo AuthConfig Limit Indexes
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    Require method GET POST OPTIONS
</Directory>

userdirモジュールはもともとDSO: dynamic shared objectで入ってる

httpd -M | grep userdir
 userdir_module (shared)

セキュリティ上の理由でデフォルト無効になっている

    #
    # UserDir is disabled by default since it can confirm the presence
    # of a username on the system (depending on home directory
    # permissions).
    #
    UserDir disabled
diff -u /etc/httpd/conf.d/userdir.conf.bak /etc/httpd/conf.d/userdir.conf 
--- /etc/httpd/conf.d/userdir.conf.bak	2020-12-31 07:03:02.408490105 +0000
+++ /etc/httpd/conf.d/userdir.conf	2020-12-31 07:04:12.710096282 +0000
@@ -14,14 +14,14 @@
     # of a username on the system (depending on home directory
     # permissions).
     #
-    UserDir disabled
+    # UserDir disabled
 
     #
     # To enable requests to /~user/ to serve the user's public_html
     # directory, remove the "UserDir disabled" line above, and uncomment
     # the following line instead:
     # 
-    #UserDir public_html
+    UserDir public_html
 </IfModule>
 
 #
httpd -t
Syntax OK
sudo systemctl reload httpd
curl localhost/~wand

まだ403

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /~wand
on this server.</p>
</body></html>

~wand/public_html/が700なのが駄目

  • apacheユーザの実行権限が必要
ls -ld ~wand
drwx------. 5 wand wand 142 Dec 31 06:56 /home/wand
chmod 701 ~wand
ls -ld ~wand
drwx-----x. 5 wand wand 142 Dec 31 06:56 /home/wand

ひとまず301は返るようになる

curl localhost/~wand/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://localhost/~wand/">here</a>.</p>
</body></html>

リダイレクトをたどるとまだ403

curl http://localhost/~wand/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /~wand/
on this server.</p>
</body></html>

SELinuxが有効だとうまくいかないらしい

getenforce
Enforcing
sudo setenforce Permissive

curl http://localhost/~wand/
hoge

OK

SELinux (Security-Enhanced Linux) の無効化自体はよくないので戻しておく

エラーログ

#
# 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"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

出力例

sudo cat /var/log/httpd/error_log
...
[Thu Dec 31 07:30:59.615811 2020] [core:error] [pid 2448] (13)Permission denied: [client ::1:41402] AH00035: access to /~wand/index.html denied (filesystem path '/home/wand/public_html/index.html') because search permissions are missing on a component of the path

アクセスログ

<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 \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{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" common

    #
    # 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>
...
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
...
    CustomLog "logs/access_log" combined
...
  • LogFormatディレクティブで名前を付けてログフォーマットを定義
  • CustomLogディレクティブで保存先とログフォーマットを指定

アクセスログ抜粋

sudo cat /var/log/httpd/access_log
...
::1 - - [31/Dec/2020:07:19:15 +0000] "GET /~wand/index.html HTTP/1.1" 403 218 "-" "curl/7.29.0"
::1 - - [31/Dec/2020:07:35:18 +0000] "GET /~wand/ HTTP/1.1" 200 5 "-" "curl/7.29.0"
  • %h

    • リモートホスト
    • ::1
  • %l

    • リモートログ名
    • -
  • %u

    • リクエストユーザ名
    • -
  • %t

    • サーバがリクエストの処理を終えた時刻
    • [31/Dec/2020:07:35:18 +0000]
  • %r

    • リクエストの最初の行
    • GET /~wand/ HTTP/1.1
  • %>s

    • ステータスコード
    • 403, 200
  • %b

    • HTTPレスポンスのヘッダ以外のバイト数
    • 5 … hoge + 0x0a改行
  • %{Referer}i

    • リファラ
    • -
  • %{User-Agent}i

    • ユーザーエージェント
    • curl/7.29.0

HostnameLookups

HostnameLookups on|off

アクセス元IPアドレスからホスト名逆引きするかしないか

  • ログに残したり、ホスト名でアクセスコントロールする場合有効化
  • パフォーマンスを高める場合無効化

Alias

cat /etc/httpd/conf.d/welcome.conf
...
Alias /.noindex.html /usr/share/httpd/noindex/index.html
Alias /noindex/css/bootstrap.min.css /usr/share/httpd/noindex/css/bootstrap.min.css
Alias /noindex/css/open-sans.css /usr/share/httpd/noindex/css/open-sans.css
Alias /images/apache_pb.gif /usr/share/httpd/noindex/images/apache_pb.gif
Alias /images/poweredby.png /usr/share/httpd/noindex/images/poweredby.png

ドキュメントルートツリー以外の場所を参照できるようにする

上記の例では、ドキュメントルート /var/www/html/外の /usr/share/httpd/以下のものを参照するためにAlias定義している

trailing-slash awareであることに注意

  • Alias /images /home/www/images とすると http://.../imagesでアクセスできるが http://.../images/ではエイリアス展開されずアクセスできない

Redirect

デフォルトで302リダイレクト

httpd.conf

...
<Directory />
Redirect / http://www.google.com
</Directory>
httpd -t
Syntax OK
sudo systemctl reload httpd

curl http://localhost/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://www.google.com">here</a>.</p>
</body></html>

ScriptAlias

    #
    # 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/ "/var/www/cgi-bin/"

CGIスクリプト用ディレクトリ指定

ErrorDocument

# 
# 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. 
#
# NOTE: if this file is removed, it will be restored on upgrades.
#
<LocationMatch "^/+$">
    Options -Indexes
    ErrorDocument 403 /.noindex.html
</LocationMatch>

外部のURI指定可能

Options

ディレクトリごとにオプション機能設定

<LocationMatch "^/+$">
    Options -Indexes
    ErrorDocument 403 /.noindex.html
</LocationMatch>
<Directory "/usr/share/httpd/icons">
    Options Indexes MultiViews FollowSymlinks
    AllowOverride None
    Require all granted
</Directory>
  • 頭に-を指定すると「使わない」の意
  • スペース区切り

オプションの例

  • ExecCGI

    • cgi-bin/ディレクトリ以外でCGIプログラムを実行できる
  • Includes

    • SSI: Server Side Include
    • HTMLファイルに <!--#include virtual="/common/header.html" --> とか書けるやつ
  • Indexes

    • DirectoryIndexで指定のファイルがない場合にファイル一覧ページを生成する
  • FollowSymLinks

    • symlink先を参照
  • ALL

    • 全部有効
  • None

    • 全部無効

10.1.4 外部設定ファイル

  • .htaccess等の外部ファイルでhttpd.confの設定を上書きする
AccessFileName .htaccess

httpd.conf側で上書きをコントロールすることもできる

AllowOverride AuthConfig Limit