Http service details (2) -- Common settings of httpd2.2 configuration files,

Source: Internet
Author: User

Http service details (2) -- Common settings of httpd2.2 configuration files,

Abstract: A service configuration file is very important. Understanding the configuration file is a prerequisite for mastering the service.

1. Introduction to common httpd-2.2 documents

(1) configuration file:

Try not to change the main configuration file and change its sub-configuration file.

/Etc/httpd/conf/httpd. confMain configuration file

/Etc/httpd/conf. d/*. ConfSelf-configuration file

Check the configuration Syntax:

Httpd-t common

Service httpd configtest centos7 not supported

Service Script:/etc/rc. d/init. d/httpd

Script configuration file:/etc/sysconfig/httpd

Service Control and startup:

Chkconfig httpd on | off

Service{Start | stop | restart | status | configtest |Reload}Httpd

Root directory of the site webpage document:


Module file path:

/Etc/httpd/modules soft connection


Main program file:


/Usr/sbin/httpd. worker

/Usr/sbin/httpd. event

Master process file: The file is automatically generated after the service is started. You can check the process pid. Do not add it manually.

/Etc/httpd/run/httpd. pid

Log File directory:


Access_log: access log

Error_log: Error Log

Help document package: httpd-manualAfter the package is pressed, restart the service and you will be able to view the help documentation.

(2) Composition of the httpd configuration file: Back up before modification to form a good habit

# Grep "Section "/Etc/httpd/conf/httpd. conf are divided into three main segments.Easy to manage.

### Section 1: Global Environment Configuration

### Section 2: 'main' server configuration master server

### Section 3: Virtual Hosts Virtual host, which is all annotated and does not exist by default

Configuration format: directive (command) value (value)

Directive: case insensitive

Value: Specifies the path. Whether the value is case sensitive depends on the file system.

2. Httpd 2.2 Common configuration: You can view help on the official website or install a help package

Vim/Etc/httpd/conf/httpd. conf configuration file

1. startup error: No Name fqdn is displayed

In the total configuration fileSearch/ServerName, Remove the comments and write them as needed. It is best to write your website name. No error will be reported when the website is started.

After modification:


2. Display Server version information

ServerTokens:Manage the response header information and display the server version information

Search/ServerTokensThe default file is OS, which can be commented out or deleted. The default value is "full ".

ServerTokens Major | Minor | Min [imal] | Prod [uctOnly] | OS | Full

Information displayed in the configuration file's settings Header

① ServerTokens Prod [uctOnly]: Server: Apache

② ServerTokens Major: Server: Apache/2

③ ServerTokens Minor: Server: Apache/2.0

④ ServerTokens Min [imal]: Server: Apache/2.0.41

⑤ ServerTokens OS: Server: Apache/2.0.41 (Unix)

6. ServerTokens Full (or not specified): Server: Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2

This setting applies to the entire server and cannot be enabled or disabled on a virtualhost-by-virtualhost basis. After version 2.0.44, this directive also controls the information presented by the ServerSignature direve ve.

Recommended: ServerTokens Prod security, the more detailed the display is, the less insecure

You can view the help information. To install the httpd-manual package, the help information is very detailed.

Instance: cur-I

In addition, you can set it on the scheduler to directly hide version information or modify it at will.

3. Modify the IP address and Port of the listener.

Search/Listen, 80 by default

Listen [IP:] PORT. Do not change it at will. It can be used only to allow access from a specific ip address and prevent access from others.

(1) If the IP address is omitted, the ip address is All IP addresses are bound to the port.

(2) Listen commandAt least one, Which can be repeated multiple times,Write multiple,Cannot be blank or commented out. Comments cannot start with the service.

Listen 80

You can enable multiple ports when you write multiple Listen 8080, but the same website is accessed.

Note: If the port is changed, you must add your own port during access.

(3) modify the listening socket and restart the service process.

3. persistent connection

Persistent Connection: a Persistent Connection is established. After each resource is obtained, the Connection is not closed. Instead, the Connection continues to wait until other requests are completed. By default, KeepAlive Off is disabled.

Disconnection condition: quantity limit: 100

Time Limit: in seconds, the httpd-2.4 supports milliseconds

Side effect: for servers with high concurrency traffic, the persistent connection function will use some requests to fail to respond.

Compromise: Use a short persistent connection time

Set: KeepAlive On | Off

KeepAliveTimeout 15

MaxKeepAliveRequests 100


GET/url http/1.1 imitation packet header


4. MPM (Multi-Processing Module) Multi-Channel Processing Module

(1)MPM working mode introduction:Prefork, worker, event(Test phase)

Prefork:Multi-process I/O model,Each process responds to a request, Default model

A main process: generates and recycles n sub-processes, creates sockets, and does not respond to requests.

Multiple child processes: work processes,Each sub-process processes a request.At the beginning of the system, multiple idle processes are generated in advance, waiting for requests,Up to 1024

Worker:Reusable multi-process I/O model and multi-process Multithreading, IIS uses this model

A main process: generates m sub-processes. Each sub-process is responsible for generating n threads. Each thread responds to one request and concurrently responds to the request: m * n

Event:Event-driven model(Worker Model variant)

A main process: generates m sub-processes, each of which directly responds to n requests and concurrently responds to requests: m * n,Dedicated threadTo manage theseKeep-aliveTypeMonitoring threadWhen there is a real request, the request is passed to the service thread. After the execution is completed, the request can be released again. This enhances the request processing capability in high concurrency scenarios.

Httpd-2.2: event test, centos6 default

Httpd-2.4: event stable, centos7 default


① Prefork MPM

② Worker MPM

③ Event MPM

Note: The httpd-2.2 does not support compiling multiple modules at the same time, so only one can be selected at the time of compilation; the rpm installation package provides three binary program files for implementing support for different MPM mechanisms

(2) Confirmation method:

Ps aux | grep httpd

The default value is/usr/sbin/httpd, that is, prefork mode.

View the module list:

ViewStaticCompiled Module


ViewStatic compilation and Dynamic LoadingModule


Dynamic module loading: takes effect immediately without restarting

Dynamic module path:/usr/lib64/httpd/modules

(3) replacing the httpd program module:

/Etc/sysconfig/httpdIn this file, modify

① HTTPD =/usr/sbin/httpd. worker is commented out by default. Switch to the worker program after removing the comment.

Restart service to take effect

Pstree-p | grep httpd: View processes and threads

Httpd. worker-L module changed, and command changed.

② Different from Httpd 2.4

Provided in dynamic module Mode

Configuration File:/etc/httpd/conf. modules. d/00-mpm.conf

Httpd-M | grep mpm

Restart service to take effect

Pstree-p | grep httpd: View processes and threads

(4) default prefork Configuration:Main configuration fileMedium,Search/prefork

<IfModule prefork. c> set according to work environment

StartServers 8 prepare eight processes as soon as the service is enabled

MinSpareServers 5 is the smallest idle process. It is reserved first and is generated if it is not enough.

MaxSpareServers 20 Max idle Processes

ServerLimit 256 maximum number of processes, up to 256

MaxClients 256 Max concurrency

MaxRequestsPerChild 4000 sub-processUpOfNumber of requests. After processing the MaxRequestsPerChild request, the child process will be terminated by the parent process, and the memory occupied by the child process will be released (when it is 0, it will never be released)


(5) default worker configuration: In the master configuration file,Search/worker

<IfModule worker. c>

StartServers 4 prepare four processes as soon as the service is enabled, 4x25 = 100 threads

MaxClients 300 up to 300 threads

MinSpareThreads 25 min idle 25 thread

MaxSpareThreads 75 is a maximum of 75 Idle threads. In conflict with the preceding thread, the service first starts four processes and then kills one process.

ThreadsPerChild 25 each sub-process has a maximum of 25 threads

MaxRequestsPerChild 0 Unlimited


(6) test performance:ABCommand yum-y install httpd-tools

AB-c 100-n 1000 http: //

-C: number of concurrent connections

-N: Total number of connections

Result: The performance of prefork and worker is not significantly different.

5. DSO: Dynamic Shared Object

① Load the dynamic module configuration:/etc/httpd/conf/httpd. conf main configuration file

Configure the loading format of the specified implementation module:Search/LoadModule

② Format:

LoadModule <mod_name> <mod_path>

The relative path can be used for the module File Path: relative to the root of the ServerRoot Service (set to/etc/httpd)

③ Httpd-M can query module information. If a module is deleted or commented out, the function of that module will be disabled, and httpd-M cannot be queried.

Therefore, when we need to use PHP, we can write it into the PHP module.


LoadModule auth_basic_module


6. Define the document page path of the 'main' server (Main site)


Format: DocumentRoot"/Path"

Purpose: Document path ing:

DocumentRoot points to the starting position of the URL path.


① Multiple lines can be written, but the lower part will overwrite the upper part, and the lower part will be used.The sub-Configuration File Include conf. d/*. conf will be overwritten by this line.

② If the configured master site does not exist, the service will fail to start!


DocumentRoot "/app/site1"


Note: SELinux and iptables must be disabled.

7. Define the site homepage


Format: DirectoryIndexIndex.html. var


① When querying http: // its sub-directories, you can open the index.html file under the directory without specifying a file.

If two files are not setTo see other settings:Settings 9By default, an error is reported;

Specific settings are displayed, such as the homepage. Sub-configuration file/etc/httpd/conf. d/Welcome. confThere are settings. If there are only/users and no index.html is found in the directory, the error page is displayed,Welcome. conf has a high priority., Security

Error Page

8. Common Website access control mechanisms

Based onThe two mechanisms specify the resourcesThere are two access control mechanisms: client source address and user account.

File System Path: Format










For example, in the main configuration file, you cannot access the settings of files starting with. ht.

URL path: Supports regular expressions and wildcards.







For example, set the sub-configuration file/etc/httpd/conf. d/welcome. conf.

Note: Regular Expressions and Wildcards are supported.


<FilesMatch "\. (gif | jpe? G | png) $ "> regular

<Files"? At. * ">Wildcard

<Location/Status> absolute pathDirectory

<LocationMatch "/(extra | special)/data">

9. Access Control Based on source address in <Directory>

(1)Options: A list of options separated by one or more blank characters. You can modify the options in the total configuration file or from the creation of a self-configuration file.

Before the option+,-Indicates adding or deleting a specified option

Common options:

Indexes: SpecifiedThe URL path does not exist.AndDefine that the home page resources are consistentWhen the resource file is set to 7, returnIndex listTo the user,Not allowed by defaultAnd is not safe. When necessary, for example, when the yum source is used

FollowSymLinks: The source file to which the access symbol is directed, for example, the link file,Allowed by default

None: Disable all

All: Allow All

Note: If a conflict exists, the subsequent settings will overwrite the frontend

Sub-directories can also be set differently from parent directories.

Example: vim/etc/httpd/conf. d/test. conf sub-configuration file

(2) AllowOverride, which achieves the same effect as the above implementation, is to put the settings under the hidden file of the directory. htaccess

Which commands related to resource access management can be stored in a specified directory?. HtaccessIn the file (specified by AccessFileName), overwrite the previous one. htaccess is set in the main configuration file

Usage: vim/etc/httpd/conf. d/test. conf

Valid only for <directory> statements

AllowOverride All: All commands are valid.

AllowOverride None: The. htaccess file is invalid.

AllowOverride AuthConfig Indexes cannot be overwritten by other commands except AuthConfig and Indexes.

In the. htaccess file, set. htaccess to the directory to be controlled, such as the bbs directory.

Vim/app/site1/. htaccess

Options + indexes-followsymlinks

(3) order, allow, deny,It is invalid in 2.4 and has another permission control.

Order:Define the effective orderWritten inBackIndicates the default rule, overwrite, and has a high priority.

Order allow, deny

Order deny, allow

Allow from, Deny from

Source Address expression method: IP address, network:


Analysis: ① if there is no conflict, both allow and deny will produce results. For example:

② If there is a conflict, it depends on who is behind, and the priority is high, but only limited to conflicting,

For example, except 107, other ip addresses in This CIDR block can access the CIDR block, but all ip addresses in This CIDR block are rejected.

③ Not set in deny and allow. check who is behind allow/deny and who has a high priority.

10. Log Settings

Log Type:




ErrorLog logs/error_log

LogLevel warn

Loglevel value options:

Debug, info, notice, warn, error

Crit, alert, emerg

Access log:Search:/LogForma

Define the access log format: LogFormat format strings,

LogFormat "% h % l % u % t \" % r \ "%> s % B \" % {Referer} I \ "\" % {User-Agent} I \ "" combined

Which log is selected below?

Log format:

CustomLog logs/access_log combined

Reference help:


Meaning of various settings: You can change what you want

• % H Client IP Address

• % L remote user. mod_ident is enabled, usually minus "-""

• % U verification (basic, digest) remote user, a minus sign "-" for non-Logon access "-"

• % T time when the server received the request

• % R First line of request, indicatingThe first line of the request message.The request's "method", "URL", and Protocol version are recorded.

• %> S lastResponse status code

• % BResponse Message Size, pure data sizeThe Unit is byte, excluding the http header of the Response Message.

• % {Referer} I indicates the value of the first "referer" in the request message, that is, the page from which the hyperlink jumps to the current page

Preventing leeching. I means the first part.

• % {User-Agent} I value of the first "User-Agent" in the request message; that is, the application sending the request

The help documentation contains

Query log: tail/var/log/httpd/access_log

11. Set the default Character Set

Adddefacharcharset UTF-8 (global) Default

ChineseCharacter Set:GBK, GB2312 (Simplified Chinese), GB18030

12. Define the path alias

Format:Alias/URL/"/PATH /"/URL/virtual directory.

Alias/download/"/rpms/pub /"

Example: ==>/rpms/pub/bash. rpm

Http:// ==>/ www/htdocs/images/logo.png

13. status page

This function requires the status_module module.

Httpd-M | grep status: Check whether this module has been loaded.

In the total configuration fileSearch/server-status

LoadModule status_module modules/ this module is loaded in the total configuration file

<Location/server-status> it was originally commented out.

The SetHandler server-status2 name can be written as long as it is used for access.

Order allow, deny

Allow from


ExtendedStatus On displays the extension information, which is also annotated by default.

Display status page

Status type:

"-" Waiting for connection "S" starting "R" is in read status

"W" Send Response "K" keep persistent connection "D" dns query

"C" is in the off state "L" record log "G" elegant termination, gentle disconnection

"R" Clears idle worker processes "." No normal process exists.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.