728x90

(PHP 4, PHP 5, PHP 7)

defined — Checks whether a given named constant exists

Description ¶

bool defined ( string $name )

Checks whether the given constant exists and is defined.

Note:

If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

Parameters ¶

name

The constant name.

Return Values ¶

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Examples ¶

Example #1 Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
    echo 
TEST;
}
?>

See Also ¶

add a note add a note

User Contributed Notes 13 notes

daniel at neville dot tk ¶
9 years ago
My preferred way of checking if a constant is set, and if it isn't - setting it (could be used to set defaults in a file, where the user has already had the opportunity to set their own values in another.)

<?php

defined
('CONSTANT') or define('CONSTANT''SomeDefaultValue');

?>

Dan.
r dot hartung at roberthartung dot de ¶
8 years ago
You can use the late static command "static::" withing defined as well. This example outputs - as expected - "int (2)" 

<?php 
  
abstract class class1 
  

    public function 
getConst() 
    { 
      return 
defined('static::SOME_CONST') ? static::SOME_CONST false
    } 
  } 
  
  final class 
class2 extends class1 
  

    const 
SOME_CONST 2
  } 
  
  
$class2 = new class2
  
  
var_dump($class2->getConst()); 
?>
Lars Lernestal ¶
6 years ago
if you want to check id a class constant is defined use self:: before the constant name:

<?php
defined
('self::CONSTANT_NAME');
?>
Shaun H ¶
10 years ago
I saw that PHP doesn't have an enum function so I created my own. It's not necessary, but can come in handy from time to time.

<?php
    
function enum()
    {
        
$args func_get_args();
        foreach(
$args as $key=>$arg)
        {
            if(
defined($arg))
            {
                 die(
'Redefinition of defined constant ' $arg);
            }

            
define($arg$key);
        }
    }
    
    
enum('ONE','TWO','THREE');
    echo 
ONE' 'TWO' 'THREE;
?>
tris+php at tfconsulting dot com dot au ¶
9 years ago
Before using defined() have a look at the following benchmarks:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn't going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical
2) if(TRUE_CONST) was almost twice as slow - I guess that the substitution isn't done at compile time (I had to double check this one!)
3) defined() is 3 times slower if the constant exists
4) defined() is 19 TIMES SLOWER if the constant doesn't exist!
5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems - me!)

May want to avoid if(defined('DEBUG'))...
vindozo at gmail dot com ¶
7 years ago
If you wish to protect files from direct access I normally use this:

index.php:

<?php
// Main stuff here
define('START',microtime());

include 
"x.php";
?>

x.php:

<?php
defined
('START')||(header("HTTP/1.1 403 Forbidden")&die('403.14 - Directory listing denied.'));
?>
passerbyxp at gmail dot com ¶
5 years ago
This function, along with constant(), is namespace sensitive. And it might help if you imagine them always running under the "root namespace":

<?php
namespace FOO\BAR
{
    const 
WMP="wmp";
    function 
test()
    {
        if(
defined("WMP")) echo "direct: ".constant("WMP"); //doesn't work;
        
elseif(defined("FOO\\BAR\\WMP")) echo "namespace: ".constant("FOO\\BAR\\WMP"); //works
        
echo WMP//works
    
}
}
namespace
{
    \
FOO\BAR\test();
}
ASchmidt at Anamera dot net ¶
1 year ago
// Checking the existence of a class constant, if the class is referenced by a variable.

class Class_A
{
    const CONST_A = 'value A';
}

// When class name is known.
if ( defined( 'Class_A::CONST_A' ) )
    echo 'Class_A::CONST_A defined';

// Using a class name variable. Note the double quotes.
$class_name = Class_A::class;
if ( defined( "$class_name::CONST_A" ) )
    echo '$class_name::CONST_A defined';

// Using an instantiated object for a variable class.
$object_A = new $class_name();
if ( defined( get_class($object_A).'::CONST_A' ) )
    echo '$object_A::CONST_A defined';
ndove at cox dot net ¶
13 years ago
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:

<?php

class Generic
{
    const 
WhatAmI 'Generic';
}

if (
defined('Generic::WhatAmI'))
{
    echo 
Generic::WhatAmI;
}

?>

Thought it may be useful to note.

-Nick
info at daniel-marschall dot de ¶
8 years ago
I found something out: defined() becomes probably false if a reference gets lost.

<?php

session_start
(); // $_SESSION created
define('SESSION_BACKUP'$_SESSION);
if (
defined('SESSION_BACKUP')) echo 'A';
session_unset(); // $_SESSION destroyed
if (defined('SESSION_BACKUP')) echo 'B';

?>

You will see "A", but not "B".
reachmike at hotpop dot com ¶
9 years ago
You may find that if you use <?= ?> to dump your constants, and they are not defined, depending on your error reporting level, you may not display an error and, instead, just show the name of the constant. For example:

<?= TEST ?>

...may say TEST instead of an empty string like you might expect. The fix is a function like this:

<?php

function C(&$constant) {
    
$nPrev1 error_reporting(E_ALL);
    
$sPrev2 ini_set('display_errors''0');
    
$sTest defined($constant) ? 'defined' 'not defined';
    
$oTest = (object) error_get_last();
    
error_reporting($nPrev1);
    
ini_set('display_errors'$sPrev2);
    if (
$oTest->message) {
        return 
'';
    } else {
        return 
$constant;
    }
}

?>

And so now you can do:

<?= C(TEST?>

If TEST was assigned with define(), then you'll receive the value. If not, then you'll receive an empty string.

Please post if you can do this in fewer lines of code or do something more optimal than toggling the error handler.
Joel ¶
10 years ago
If your constants don't show up in your included or required files, then you probably have php safe mode turned on!

I ran into this problem, I forgot to turn of safe mode when I was creating a new site.
Anonymous ¶
9 months ago
Be careful with boolean defines and assuming a check is done for a specific value by defined such as
<?php

define
('DEBUG'false);

if(
defined('DEBUG')){
    echo 
'Not really debugging mode';
}
?>

You want to also check the constant as in

<?php
define
('DEBUG'true);

if(
defined('DEBUG') && DEBUG){
    echo 
'Really this is debugging mode';
}
?>

All defined is doing is verifying the constant exists not it's value.


728x90

(문서는 apache 2.2.x 버전을 기반으로 작성 되었음을 알려드립니다. 최신버전인 2.4.x 버전의 경우

2.2.x버전과는 설정 값이 다소 다르므로 유의 하시기 바랍니다.)

 

1. MPM 이란?

Multi-Processing Module

apache 가 받아 들인 요청을 처리 하기 위해 'child processes'에게 분배하는 방식을 말합니다.

 

2. 간략한 설명

1) 확장성이 필요한 사이트는 worker방식을 택하고, 안정성과 오래된 소프트웨어와 호환성이 필요한 사이트는 Prefork를 보편적으로 사용합니다.

2) Linux의 경우, Prefork 방식이 기본 설정이며, Worker방식을 사용하기 위해서는 설치 시에 -with-mpm=worker 옵션을 주어 설치합니다.

 

3. Prefork

1) 실행중인 프로세스 복제하여 실행 (메모리 영역까지 같이 복제)

2) 프로세스가 소비하는 메모리가 많음.

3) 응답프로세스를 미리 띄워놓고 클라이언트 요청 시 자식 프로세스가 반응하게 되는 방식.

4) 안전하지 않은 제 3자가 만든 모듈 사용 가능

5) 디버깅이 빈약한 플랫폼에서 쉬운 디버깅 가능

6) 일반적으로 single CPU 또는 Dual CPU에서 성능이 좋음

 

4. Worker

1) 자식 프로세스들이 각각 여러 쓰레드를 사용하며, 각 쓰레드는 한번에 한 연결을 담당

2) Worker 방식은 일반적으로 멀티 CPU 시스템에서 성능이 좋다

3) 요청을 쓰레드 단위로 처리 ( 최대 64개의 쓰레드 처리 가능 )

4) 지정된 만큼의 프로세스와 각 쓰레드를 준비하여 클라이언트의 요청을 받아들이는 설정

5) 기본 사용 메모리는 prefork보다 낮으며 쓰레드 간에 메모리를 서로 공유함

6) 동시접속자가 많은 사이트에 적합



5. Prefork  Worker 방식이 차이점

1) Worker Prefork에 비해 적은 메모리 사용한다.

2) Worker : 통신량이 많은 서버에 적절한 형태를 가진다.

3) Prefork : 안전하지 않은 제 3자가 만든 모듈을 사용할 수 있다.

4) Prefork : 디버깅이 빈약한 플랫폼에서 쉽게 디버깅 할 수 있다.

5) Worker‘ 와 ‘Prefork‘ 의 속도는 비슷하다.

 

6. event

요청과 Keep Alive한 아파치 요청을 그대로 맺는 것이 아니라, 요청을 처리하는 쓰레드를 따로 두도록 하여 분산된 처리를 할 수 있게 하는데 목적을 둔 2.4.x 버전부터 생성된 방식

 

*  mpm 방식 및 다른 웹서버 엔진에 대한 성능 테스트는 아래의 사이트에 자세히 나와있으므로 참조하시기 바랍니다.

http://www.atlanticdynamic.com/web-server-performance-analysis-2012/

 


 

7. 설치 방법

 

Apache 컴파일시 --with-mpm=worker 혹은 –with-mpm=prefrork 옵션 추가

 

1) prefork

2.2.x 버전의 경우 별도의 옵션이 없이 컴파일 시에 별도 옵션은 필요없습니다.

2.4.x의 경우 컴파일시 다음 옵션 추가 --with-mpm=prefork

(* 2.4.x 버전의 경우 별도 옵션이 없다면 event로 설치됩니다.)

 

2) worker

2.2.x, 2.4.x의 경우 컴파일시 다음 옵션 추가 --with-mpm=worker

(* 2.4.x 버전의 경우 별도 옵션이 없다면 event로 설치됩니다.)

 

3) event

2.4.x 버전부터 적용되는 방식이며, 컴파일시 별도 옵션이 없는 경우 기본값

 

8. Max Clients 수정

1) Prefork

- apache 1.x

Apache 소스파일 디렉토리에서 vi 편집기를 통해 src/include/httpd.h 파일에서 HARD_SERVER_LIMIT 256 (256 -> 1024로 변경)

수정 구문

define HARD_SERVER_LIMIT 1024

 

- apache 2.x

Apache 소스파일 디렉토리에서 vi 편집기를 통해 /server/mpm/prefork/prefork.c 파일에서

#define DEFAULT_SERVER_LIMIT 2048 (256 -> 2048로 변경

 

수정 구문

#define DEFAULT_SERVER_LIMIT 256 -> #define DEFAULT_SERVER_LIMIT 2048

 

2) Worker

apache 2.x 버젼에만 존재합니다.

MaxClients  StartServers  ThreadsPerChild 의 곱에 의해서 결정됩니다

MaxClients = StartServer * ThreadsPerChild

worker 방식은 각각의 자식 프로세스 별로 여러개의 쓰레드를 생성하여 요청을 처리하기

때문입니다.

32 * 64 = 2048

 

Maxclient를 늘리기 위한 설정

Apache 소스파일 디렉토리에서 vi 편집기를 통해 아파치설치폴더/server/mpm/worker/worker.c 파일에서 #define DEFAULT_SERVER_LIMIT 32 (16 -> 32로 변경)

 

수정 구문

#define DEFAULT_SERVER_LIMIT 32 (16 -> 32로 변경)

 

(httpd 1.x 버전은 prefork 방식만 가능하며 worker 2.x부터  가능합니다.)

 

9. 설정

 

1) httpd.conf 수정

- 아래와 같이. "Include conf/extra/httpd-mpm.conf" 설정의 주석을 제거

(기본적으로 주석처리 되어 있음)

===============================

# Server-pool management (MPM specific)

Include conf/extra/httpd-mpm.conf

===============================

이후 vi 편집기를 통해 apache 설치경로/conf/extra/httpd-mpm.conf 파일을 열어 수정합니다.

 

2) Prefork 방식

- 하나의 자식 프로세스가 하나의 쓰레드를 갖는 구조로, 자식 프로세스는 1024까지 늘일 수 있습니다.

- 한개의 자식 프로세스는 한 개의 연결을 담당.

- 프로세스가 생성되는 구조이므로 당연히 worker보다는 많은 메모리를 사용.

- 프로세스간 메모리를 직접 공유하지 않으므로, 메모리 공간이 독립적이어서 안정적

/apache 설지경로/conf/extra/httpd-mpm.conf 파일에서

  <IfModule mpm_prefork_module>

      StartServers 5

      MinSpareServers 5

      MaxSpareServers 10

      MaxClients 150

      MaxRequestsPerChild 0

  </IfModule>

 

- 옵션 설명


l StartServer

아파치서버의 자식 프로세스 개수 지정

 

l MinSpareServers, MaxSpareServers

부하가 적어서 MinSpareServers 개수 보다 적었을 경우 최소한 이 개수 만큼 아파치가 유지하려 하며, 부하가 증가하여 프로세스 개수가 많아질 경우에 MaxSpareServers 개수 이하로 줄이려고 아파치가 구동 됩니다. 절대적인 수치는 아닙니다.

 

l  MaxClient

초기 시작시 실행가능한 최대 아파치 자식 프로세스의 개수를 지정

worker방식의 MaxClient 와는 다른 의미가 다르지만 클라이언트의 요청을 처리하는 용량을

말하므로 비슷한 의미로 보시면 됩니다.


 l  MaxReqeustPerChild

클라이언트들의 요청 개수를 제한.

만약 자식 프로세스가 이 값만큼의 클라이언트 요청을 받았다면 이 자식 프로세스는 자동으로 kill 됩니다.

(0 인 경우 무한대)

 

3) Worker 방식

- 자식 프로세스들이 여러개의 쓰레드를 갖을 수 있으며, 각 쓰레드는 한번에 한 연결을 담당합니다.

- Prefork보다 메모리 사용량이 적으며, 통신량이 많은 서버에 적절합니다.

- 쓰레드 간에 메모리 공간을 공유하며, 리소스 경합이 발생하지 않도록 주의 필요. 특히 PHP를 쓰는 경우 유의하여야 합니다.

 

/apache 설지경로/conf/extra/httpd-mpm.conf 파일에서

 

    <IfModule mpm_worker_module>

        StartServers 2

        MaxClients 150

        MinSpareThreads 25

        MaxSpareThreads 75

        ThreadsPerChild 25

        MaxRequestsPerChild 0

    </IfModule>

 

옵션 설명 


l  StartServers(Default 3)

시작시에 생성되는 서버 프로세스의 개수, 자식 프로세스의 수는 부하에 따라 동적으로 변경되기 때문에 이 값은 큰 의미가 없습니다.

 

l  ServerLimit (default : 16)                                                                                                                          

구성 가능한 child 프로세스의 제한 수.

ServerLimit 값이 필요 이상 높게 설정 된다면, 불필요한 공유 메모리가 할당 되므로 적절한 설정 필요합니다.

MaxClient  ThreadPerChild 에서 요구한 프로세스 수보다 높게 설정하지 마시기 바랍니다.

 

l  MaxClient (default : ServerLimit * ThreadsPerChild)

동시에 처리될 최대 커넥션(request)의 수

MaxClients 수치를 초과한 후 온 요청들은 ListenBackLog에 의해 큐잉됩니다.

ThreadsPerChild 옵션과 매우 긴밀하게 작용

동접자가 많을 경우,  MaxClient값을 증가시켜야 합니다.

OS FD(File Descriptor)값을 증가 시켜 MaxClient 의 상한값을 증가시키시기 바랍니다.

 

l  MinSpareThreads(default 75)

최소 thread 개수

만약 서버에 idle 쓰레드가 충분하지 않다면 child 프로세스는 idle 쓰레드가 MinSpareThreads 보다 커질때까지 생성됩니다.

 

l  MaxSpareThreads(default 250)

최대 thread개수

만약 서버에 너무 많은 idle 쓰레드가 존재하면 child 프로세스는 idle 쓰레드가 MaxSpareThreads 수보다 작아질 때까지 kill 됩니다.

  

l  ThreadPerChild

개별 자식 프로세스가 지속적으로 가질 수 있는 Thread의 개수

 

l  MaxRequestPerChild

자식 프로세스가 서비스할 수 있는 최대 요청 개수

 

l  ThreadLimit (default : 64)

child 프로세스의 라이프주기 동안 ThreadsPerChild 의 최대 설정값을 설정합니다.

ThreadLimit  ThreadsPerChild 보다 훨씬 높게 설정된다면, 여분의 미사용 공유 메모리가 할당될 것입니다.

ThreadLimit  ThreadsPerChild 모두 시스템이 감당할 수 있는 값 보다 높게 설정하면,

아파치가 기동되지 않거나 시스템이 불안정하게 될 수 있습니다.

* 이 값은 최대 예상 ThreadsPerChild 의 설정보다 높게 설정하면 안됩니다.

 

 

10. 참고

 

1) 대부분 prefork 방식이 기본적으로 사용되며, 사용자가 많은 경우에는 worker방식을 사용

 요즘 몇 몇 사이트에서 사용자가 많은 경우 worker 방식을 사용하는 경우가 있습니다.

 

2) 현재 worker 모듈 설치 되었는지 확인하는 방법

/apapche 설치경로/bin/ "httpd -l" 명령으로 현재 설치된 Apache worker방식으로 설치되었는지 확인할 수 있습니다.

============================================

Compiled in modules:

  core.c

  worker.c

  http_core.c

  mod_so.c

============================================

 

또는, httpd -V 명령으로 확인 가능합니다. (V는 대문자)

============================================

# httpd -V

Server version: Apache/2.2.15 (Unix)

Server built:   Jun 30 2010 16:59:45

Server's Module Magic Number: 20051115:24

Server loaded:  APR 1.4.2, APR-Util 1.3.9

Compiled using: APR 1.4.2, APR-Util 1.3.9

Architecture:   32-bit

Server MPM:     Worker

  threaded:     yes (fixed thread count)

    forked:     yes (variable process count)

Server compiled with....

 -D APACHE_MPM_DIR="server/mpm/worker"

 -D APR_HAS_SENDFILE

 -D APR_HAS_MMAP

 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)

 -D APR_USE_SYSVSEM_SERIALIZE

 -D APR_USE_PTHREAD_SERIALIZE

 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT

 -D APR_HAS_OTHER_CHILD

 -D AP_HAVE_RELIABLE_PIPED_LOGS

 -D DYNAMIC_MODULE_LIMIT=128

 -D HTTPD_ROOT="/home/paint/apache-2.2.15"

 -D SUEXEC_BIN="/home/paint/apache-2.2.15/bin/suexec"

 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"

 -D DEFAULT_ERRORLOG="logs/error_log"

 -D AP_TYPES_CONFIG_FILE="conf/mime.types"

 -D SERVER_CONFIG_FILE="conf/httpd.conf"

=============================================


'APACHE TUNE' 카테고리의 다른 글

Apache 벤치마크 유틸리티 사용  (0) 2018.05.05
defined  (0) 2018.05.04
WHAT & HOW TO CONFIGURE APACHE MULTI-PROCESSING MODULES (MPMS)  (0) 2018.04.21
Optimize Apache Performance on CentOS 7  (0) 2018.04.21
Apache MPM Common Directives  (0) 2018.04.21
728x90

Are you worried about your Apache server performance? Okay let’s talk about Apache Multi-Processing Modules (MPMs). There is a documentation for Apache MPM but who has got time to read the documentations. Let’s talk in simple plain english about Apache Multi-Processing Modules (MPMs). All you need is 15 mins to learn Apache MPMs(happy-face).

What

The MPMs are used to change the basic functionality of the web server. It’s possible due to Apache’s modular design. The MPM, or Multi Processing Module, you use is responsible for just about the entire HTTP session. Starting from listening on the network, taking requests in and most importantly, how to handle those requests. With the MPM you use Apache’s behaviour will change. Apache offers three MPMs to choose from; PreforkWorker, and Event. You might be wondering which MPM module you should choose. Answer is right below.

How do I select which Apache MPM to use?

Above links explains about the three MPM modules and when to use them. If you don’t know about the Apache MPMs or which one to use , time to start reading.

How

1. Check what your Apache server has got

Most of the Apache server comes with Prefork module. To make sure whether your server has got Prefork, type the below command and see.

See the output below

If the Prefork Module is installed it should be shown under compiled in modules. prefork.c is shown on the list.

2. Let’s install Apache Worker MPM

Let’s configure Worker MPM. So time to install Worker.

If you are willing to install Prefork or Event MPMs it should be as below

When the installation is completed type apache2ctl -l and see whether the prefork.c/worker.c shows up under “Compiled in modules”.

Note in Ubuntu you can only have one MPM module at a time. It means if you install Worker while the server has got Prefork, Prefork will be automatically removed. When you are switching MPMs it’s a good idea to backup your .conf files.

3. Let’s understand Apache MPM directives

Please read the comments below to understand about the each directives and what they do. Below configurations are extracted from apache2.conf

If you need more information on directives check the documentation.

4. Time to customise the Apache Worker directives as we need

 

Before customising the directives you need to understand how the directives work. Let me explain in plain English. Server will start 2 child processes which is determined by StartServersdirective. Each process will start 20 threads which is determined by ThreadsPerChild directive so this means 2 process can service only 40 concurrent connections/clients(i.e. 20×2=40). So what if more requests come in.

Now if more concurrent users come, then another child process will start, that can serve another 20 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 10 child processes in total, with each child process can handle 20 thread, in total handling 10×20=200 concurrent users.

But there is a problem, number defined in MaxClients is 100 here, this means that after 5 child processes, no extra process will start since we have defined an upper cap of MaxClients. This also means that if I set MaxClients to 500, after 10 child processes and 200 connections, no extra process will start and we cannot service more than 200 concurrent clients even if we have increase the MaxClient parameter. In this case, we need to also increase ServerLimit to 500/20 i.e. MaxClients/ThreadsPerChild=25

Okay now you know the directives and how they work, the problem is how to calculate the directives. Let’s jump into calculating directive values.

You can use this shell script to determine an average amount of memory consumed by one Apache process. In addition to that it’ll show total amount of memory consumed by all Apache processes. Just unzip and execute with sh command. Accurate results will be shown when server is under heavy load.

The output

if in average, let’s assume that one Apache process consumes 50MB RAM and server has got RAM is 2048MB, and you want to leave 512MB for the rest of the processes, then:

So that’s how you configure Apache Multi-Processing Modules. If you have any questions let me know in the comments below. Your feedback is highly appreciated(happy-face).

Image Courtesy : http://www.vps.net/

728x90

Table of Contents

Introduction

Apache is a powerful and capable open-source web server, designed to provide a balance of flexibility, portability, and performance. Apache optimization is an important task for every system administrator.

You can improve Apache's performance by customizing the Apache configuration without needing to add additional hardware like RAM, CPU etc.

This post describes various Apache configuration options that can be used to improve Apache performance without adding additional hardware resources to your system.

Requirements

  • A server running CentOS v.7
  • Apache installed and running

MaxKeepAliveRequests

MaxKeepAliveRequests is the maximum number of requests to serve on a TCP connection. It limits the number of requests allowed per connection. If it is set to 0, unlimited requests will be allowed. You can set it to any value you desire.

Keep this setting to a high value for maximum server performance. The recommended value of MaxKeepAliveRequests is 500.

To change this setting, edit the Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

MaxKeepAliveRequests 500

Save and close the file when you are finished.

KeepAliveTimeout

KeepAliveTimeout defines the number of seconds Apache will wait for the new request from connected clients before closing the connection. (Once the server receives a request, the Timeout directive applies instead.)

By default Keepalive is disabled in CentOS 7. If Keepalive is set to on, it is a good idea to set the KeepAliveTimeout value low.

The recommended KeepAliveTimeout can be between 1 to 5.

You can do this by editing Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

KeepAliveTimeout 5

Save and close the file when you are finished.

KeepAlive

KeepAlive sets whether the server allows more than one request per connection. It can be used to prevent any one client from consuming too much of the server's resources.

By default KeepAlive is disabled in CentOS 7. Once the Apache server is getting requests from hundreds and thousands of IPs at once, this setting should be On.

You can enable this setting by editing Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

KeepAlive On

Save and close the file when you are finished.

Configure MPM Prefork

One reason for poor Apache performance is that Apache is having trouble coping with the load. The Apache MPM (Multi-Processing Module) can help.

mpm_prefork_module is included and enabled in the default Apache installation on CentOS 7. To confirm this run the following command:

sudo apachectl -t -D DUMP_MODULES |grep mpm

You should see mpm_prefork_module (shared) if mod_deflate is installed and enabled.

You can make Apache performance better using the Apache MPM prefork module. To do this, set the following parameters in your Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following lines:

KeepAlive Off
<IfModule prefork.c>
   StartServers        5
   MinSpareServers     5
   MaxSpareServers     10
   MaxClients          150
   MaxRequestsPerChild 3000
</IfModule>

Save and close the file, then restart Apache to reflect these changes.

sudo apachectl restart

Explanations

StartServers: This directive sets the number of child server processes created on startup. It is a good idea to increase this number on a high-load server, so the server is ready to handle a lot of connections.

MinSpareServers: This directive sets the minimum number of idle child server processes. This value will need to be tuned for high-load servers.

MaxSpareServers: This directive sets the maximum number of idle child server processes. When there are more idle child server processes than defined by MaxSpareServers the idle process will be killed.

MaxClients: This directive sets the maximum number of simultaneous requests that Apache will handle. When this limit has been reached, any other connection attempts will be queued.

Number of MaxClients = (Total RAM memory – RAM memory used for other process except Apache process) / (Memory used by a single Apache process)

MaxRequestsPerChild: This directive sets how many requests a child process will handle before terminating. Once the limit has been reached, the child process will die.

Note: If this value is 0, then the process will never die.

AllowOverride

If AllowOverride is set to 'All', then Apache will attempt to open a .htaccess file in each directory that it visits.

For example:

 DocumentRoot /vaw/www/html/website1
 <Directory /> 
 AllowOverride All
 </Directory>

If a request is made for URI /index.html, then Apache will attempt to open .htaccess file in //var//var/www//var/www/html/ and /var/www/html/website1/.

Therefore, it is good idea to add AllowOverride all for a specific directory only:

 DocumentRoot /vaw/www/html/example
 <Directory /var/wwww/html/example/admin> 
   AllowOverride All
 </Directory>

DNS Lookups

The biggest reason for Apache web server slowdowns is the time required to perform DNS lookups. Apache will record the full host name of each incoming client connection in its access.log file. Resolving each one eats up a significant chunk of time.

The HostnameLookups option enables DNS lookup so that hostnames can be logged instead of the IP address. By default HostnameLookups is Off in Apache.

You can verify that this is the case by editing the Apache config file:

sudo nano /etc/httpd/conf/httpd.conf

Be sure the HostnameLookups line reads:

HostnameLookups Off

Save and close the file when you are finished, then restart Apache to reflect changes.

sudo apachectl restart

Conclusion

Configuring Apache for maximum performance is very easy. You can experiment with various available options and measure the web server performance with tools like ab and httperf. Feel free to leave me a comment if you have any questions.

+ Recent posts