LAMP之Apache

Apache是世界使用排名第一的Web服務器軟件。它能夠運行在幾乎全部普遍使用的計算機平臺上,因爲其跨平臺和安全性被普遍使用,是最流行的Web服務器端軟件之一。快速、可靠而且可經過簡單的API擴充,將Perl/Python解釋器編譯到服務器中。javascript

特色:php

  功能強大、配置簡單、速度快、應用普遍、性能穩定可靠,同時還能夠作代理服務器或負載均衡css

應用場景:html

  運行靜態頁面、圖片(聽說處理靜態小文件能力不如Nginx)java

  結合PHP引擎運行PHP等程序,LAMP組合node

  結合tomcat、resin運行jsp、java等程序web

  做代理、負載均衡,rewrite規則過濾等redis

一、Apache的安裝

檢查系統是否自帶httpd(通常自帶版本比較低,卸載掉)express

[root@localhost1 software]# rpm -qa httpd*
[root@localhost1 software]# 
2、若是沒有自帶 Apache 服務軟件,能夠不須要進行下面的卸載
[root@Centos ~]# rpm -e --nodeps httpd-2.2.15-54.el6.centos.x86_64
warning: /etc/httpd/conf/httpd.conf saved as /etc/httpd/conf/httpd.conf.rpmsave
[root@Centos ~]# rpm -e --nodeps httpd-tools-2.2.15-54.el6.centos.x86_64
[root@localhost1 ~]# cd /home/cairui/
[root@localhost1 cairui]# ls
[root@localhost1 cairui]# mkdir software
[root@localhost1 cairui]# cd software/
[root@localhost1 software]# wget http://mirrors.hust.edu.cn/apache//httpd/httpd-2.2.34.tar.gz
--2018-02-26 16:16:06--  http://mirrors.hust.edu.cn/apache//httpd/httpd-2.2.34.tar.gz
Resolving mirrors.hust.edu.cn... 202.114.18.160
Connecting to mirrors.hust.edu.cn|202.114.18.160|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7684419 (7.3M) [application/octet-stream]
Saving to: 「httpd-2.2.34.tar.gz」

100%[====================================>] 7,684,419    212K/s   in 45s     

2018-02-26 16:16:52 (167 KB/s) - 「httpd-2.2.34.tar.gz」 saved [7684419/7684419]

[root@localhost1 software]# ls
httpd-2.2.34.tar.gz
[root@localhost1 httpd-2.2.34]# tar zxvf httpd-2.2.34.tar.gz 
[root@localhost1 software]# cd httpd-2.2.34
[root@localhost1 httpd-2.2.34]# ll
total 1176
-rw-r--r--  1 1001 1001  14882 Nov 21  2004 ABOUT_APACHE
-rw-r--r--  1 1001 1001  18613 Jul  6  2012 acinclude.m4
-rw-r--r--  1 1001 1001  56952 Oct  5  2010 Apache.dsw
drwxr-xr-x  6 1001 1001   4096 Jul  6  2017 build
-rw-r--r--  1 1001 1001   2644 Aug 24  2007 BuildAll.dsp
-rw-r--r--  1 1001 1001   2692 Jul 29  2009 BuildBin.dsp
-rwxr-xr-x  1 1001 1001   5786 Sep 19  2012 buildconf
-rw-r--r--  1 1001 1001 147887 Jun 28  2017 CHANGES
-rw-r--r--  1 1001 1001  11701 Feb 27  2012 config.layout
-rwxr-xr-x  1 1001 1001 574593 Jul  6  2017 configure
-rw-r--r--  1 1001 1001  24720 May 25  2015 configure.in
drwxr-xr-x  9 1001 1001   4096 Jul  6  2017 docs
-rw-r--r--  1 1001 1001    403 Nov 21  2004 emacs-style
-rw-r--r--  1 1001 1001   1248 May  7  2011 httpd.dep
-rw-r--r--  1 1001 1001   4124 Jun 11  2008 httpd.dsp
-rw-r--r--  1 1001 1001   8994 May  6  2011 httpd.mak
-rw-r--r--  1 1001 1001  12053 Jul  6  2017 httpd.spec
drwxr-xr-x  2 1001 1001   4096 Jul  6  2017 include
-rw-r--r--  1 1001 1001   5129 Jan  9  2017 INSTALL
-rw-r--r--  1 1001 1001   2909 Dec  7  2006 InstallBin.dsp
-rw-r--r--  1 1001 1001   5145 Nov 29  2005 LAYOUT
-rw-r--r--  1 1001 1001  30119 May  7  2011 libhttpd.dep
-rw-r--r--  1 1001 1001  17039 Jan 12  2007 libhttpd.dsp
-rw-r--r--  1 1001 1001  28503 May  6  2011 libhttpd.mak
-rw-r--r--  1 1001 1001  28690 Jan 18  2008 LICENSE
-rw-r--r--  1 1001 1001   8739 Nov 25  2008 Makefile.in
-rw-r--r--  1 1001 1001  34759 Jan 19  2014 Makefile.win
drwxr-xr-x 20 1001 1001   4096 Jul  6  2017 modules
-rw-r--r--  1 1001 1001    828 Jan  2  2017 NOTICE
-rw-r--r--  1 1001 1001  12894 Mar 15  2012 NWGNUmakefile
drwxr-xr-x  9 1001 1001   4096 Jul  6  2017 os
-rw-r--r--  1 1001 1001   5954 Jan 10  2007 README
-rw-r--r--  1 1001 1001   4178 Aug 27  2014 README.platforms
-rw-r--r--  1 1001 1001   2553 Dec 20  2010 README-win32.txt
-rw-r--r--  1 1001 1001  10183 Mar 14  2005 ROADMAP
drwxr-xr-x  3 1001 1001   4096 Jul  6  2017 server
drwxr-xr-x  5 1001 1001   4096 Jul  6  2017 srclib
drwxr-xr-x  4 1001 1001   4096 Jul  6  2017 support
drwxr-xr-x  2 1001 1001   4096 Jul  6  2017 test
-rw-r--r--  1 1001 1001   8183 Oct 17  2005 VERSIONING
[root@localhost1 httpd-2.2.34]# cat README

                          Apache HTTP Server

  What is it?
  -----------

  The Apache HTTP Server is a powerful and flexible HTTP/1.1 compliant
  web server.  Originally designed as a replacement for the NCSA HTTP
  Server, it has grown to be the most popular web server on the
  Internet.  As a project of the Apache Software Foundation, the
  developers aim to collaboratively develop and maintain a robust,
  commercial-grade, standards-based server with freely available
  source code.

  The Latest Version
  ------------------

  Details of the latest version can be found on the Apache HTTP
  server project page under <http://httpd.apache.org/>.

  Documentation
  -------------

  The documentation available as of the date of this release is
  included in HTML format in the docs/manual/ directory.  The most
  up-to-date documentation for the 2.2.x releases can be found at
  <http://httpd.apache.org/docs/2.2/>.

  Installation
  ------------

  Please see the file called INSTALL.  Platform specific notes can be
  found in README.platforms.

  Licensing
  ---------

  Please see the file called LICENSE.

  Cryptographic Software Notice  #加密軟件的通知
  -----------------------------

  This distribution may include software that has been designed for use
  with cryptographic software.  The country in which you currently reside
  may have restrictions on the import, possession, use, and/or re-export
  to another country, of encryption software.  BEFORE using any encryption
  software, please check your country's laws, regulations and policies
  concerning the import, possession, or use, and re-export of encryption
  software, to see if this is permitted.  See <http://www.wassenaar.org/>
  for more information.

  The U.S. Government Department of Commerce, Bureau of Industry and
  Security (BIS), has classified this software as Export Commodity 
  Control Number (ECCN) 5D002.C.1, which includes information security
  software using or performing cryptographic functions with asymmetric
  algorithms.  The form and manner of this Apache Software Foundation
  distribution makes it eligible for export under the License Exception
  ENC Technology Software Unrestricted (TSU) exception (see the BIS 
  Export Administration Regulations, Section 740.13) for both object 
  code and source code.

  The following provides more details on the included files that
  may be subject to export controls on cryptographic software:

    Apache httpd 2.0 and later versions include the mod_ssl module under
       modules/ssl/
    for configuring and listening to connections over SSL encrypted
    network sockets by performing calls to a general-purpose encryption
    library, such as OpenSSL or the operating system's platform-specific
    SSL facilities.

    In addition, some versions of apr-util provide an abstract interface
    for SSL encrypted network sockets in the files under the directory
       srclib/apr-util/ssl/
    that makes use of a general-purpose encryption library, such as
    OpenSSL or the operating system's platform-specific SSL facilities.
    Apache httpd currently does not use that apr-util interface.

    Some object code distributions of Apache httpd, indicated with the
    word "crypto" in the package name, may include object code for the
    OpenSSL encryption library as distributed in open source form from
    <http://www.openssl.org/source/>.

  The above files are optional and may be removed if the cryptographic
  functionality is not desired or needs to be excluded from redistribution.
  Distribution packages of Apache httpd that include the word "nossl"
  in the package name have been created without the above files and are
  therefore not subject to this notice.

  Contacts
  --------

     o If you want to be informed about new code releases, bug fixes,
       security fixes, general news and information about the Apache server
       subscribe to the apache-announce mailing list as described under
       <http://httpd.apache.org/lists.html#http-announce>

     o If you want freely available support for running Apache please join the
       Apache user community by subscribing to Users Mailing List at
       <http://httpd.apache.org/userslist.html> or one of the following
       USENET newsgroups:
         comp.infosystems.www.servers.unix
         comp.infosystems.www.servers.ms-windows
       Also available at: 
         <http://groups.google.com/groups?group=comp.infosystems.www.servers>

     o If you want commercial support for running Apache please contact
       one of the companies and contractors which are listed at
       <http://www.apache.org/info/support.cgi>

     o If you have a concrete bug report for Apache please go to the
       Apache Group Bug Database and submit your report:
       <http://httpd.apache.org/bug_report.html>

     o If you want to participate in actively developing Apache please
       subscribe to the `dev@httpd.apache.org' mailing list as described at
       <http://httpd.apache.org/lists.html#http-dev>

  Acknowledgments
  ----------------

  We wish to acknowledge the following copyrighted works that
  make up portions of the Apache software:

  Portions of this software were developed at the National Center
  for Supercomputing Applications (NCSA) at the University of
  Illinois at Urbana-Champaign.

  This software contains code derived from the RSA Data Security
  Inc. MD5 Message-Digest Algorithm, including various
  modifications by Spyglass Inc., Carnegie Mellon University, and
  Bell Communications Research, Inc (Bellcore).

  Regular expression support is provided by the PCRE library package, which
  is open source software, written by Philip Hazel, and copyright by the
  University of Cambridge, England.  The original software is available from
     ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/

  Apache 2 relies heavily on the use of autoconf and libtool to provide
  a build environment.
[root@localhost1 httpd-2.2.34]# cat INSTALL 

  APACHE INSTALLATION OVERVIEW

  CAUTION
  -------

  This package represents a legacy version of the Apache HTTP Server software
  and is not current.

  Please note that Apache Web Server Project will only provide maintenance
  releases of the 2.2.x flavor through June of 2017, and will provide some
  security patches beyond this date through at least December of 2017.
  Minimal maintenance patches of 2.2.x are expected throughout this period,
  and users are strongly discouraged from deploying this legacy release.    #不建議安裝較低版本,由於不會再維護

  Also note, this package includes very stale and known-vulnerable versions
  of the Expat [http://expat.sourceforge.net/] and PCRE [http://www.pcre.org/]
  packages. Users are strongly encouraged to first install the most recent
  versions of these components.                            #強烈建議安裝最新版本


  Quick Start - Unix
  ------------------

  For complete installation documentation, see [ht]docs/manual/install.html or
  http://httpd.apache.org/docs/2.2/install.html

     $ ./configure --prefix=PREFIX
     $ make
     $ make install
     $ PREFIX/bin/apachectl start

     NOTES: * Replace PREFIX with the filesystem path under which 
              Apache should be installed.  A typical installation
              might use "/usr/local/apache2" for PREFIX (without the
              quotes).

            * If you are a developer who will be linking your code with
              Apache or using a debugger to step through server code,
              ./configure's --with-included-apr option may be advantageous,
              as it removes the possibility of version or compile-option
              mismatches with APR and APR-util code.  (Many OSes now
              include their own version of APR and APR-util.)

            * If you are a developer building Apache directly from
              Subversion, you will need to run ./buildconf before running
              configure. This script bootstraps the build environment and
              requires Python as well as GNU autoconf and libtool. If you
              build Apache from a release tarball, you don't have to run
              buildconf.

            * If you want to build a threaded MPM (for instance worker)
              on  FreeBSD, be aware that threads do not work well with
              Apache on FreeBSD versions before 5.4-RELEASE. If you wish
              to try a threaded Apache on an earlier version of FreeBSD,
              use the --enable-threads parameter to ./configure in
              addition to the --with-mpm parameter.

            * If you are building directly from Subversion on Mac OS X
              (Darwin), make sure to use GNU Libtool 1.4.2 or newer. All
              recent versions of the developer tools on this platform
              include a sufficiently recent version of GNU Libtool (named
              glibtool, but buildconf knows where to find it).

  For a short impression of what possibilities you have, here is a
  typical example which configures Apache for the installation tree
  /sw/pkg/apache with a particular compiler and flags plus the two
  additional modules mod_rewrite and mod_speling for later loading
  through the DSO mechanism:

     $ CC="pgcc" CFLAGS="-O2" \
     ./configure --prefix=/sw/pkg/apache \
     --enable-rewrite=shared \
     --enable-speling=shared 

  The easiest way to find all of the configuration flags for Apache 2.2
  is to run ./configure --help.


  Quick Start - Windows
  ---------------------

  For complete documentation, see manual/platform/windows.html.en or
  http://httpd.apache.org/docs/2.2/platform/windows.html.

  The Apache/Win32 binaries are distributed as Windows Installer packages 
  (.msi) named httpd-2.2.xx-win32-x86-no_ssl.msi for a version without mod_ssl
  and httpd-2.2.xx-win32-x86-openssl-0.9.8x.msi for a version including the
  mod_ssl plus the openssl library and command line utility.  These packages
  may be unpacked without "installing" them by using the msiexec /a option.

  If you have unpacked a source distribution (named httpd-2.2.x-win32-src.zip, 
  without any -x86 notation) you must compile the package yourself, see the links
  mentioned above.  Unless you intended to do this, please look again for the 
  binary package from http://www.apache.org/dist/httpd/binaries/win32/ and
  install the desired .msi package.

  The .msi package configures the httpd.conf file, and installs and starts 
  the Apache2.2 service for you.  It also installs plenty of useful shortcuts
  and the taskbar ApacheMonitor.  We strongly encourage you to use it.


  Postscript
  ----------

  The Apache HTTP Server group cannot field user's installation questions.
  There are many valuable forums to help you get started.  Please refer your
  questions to the appropriate forum, such as the Users Mailing List at
  http://httpd.apache.org/userslist.html or the usenet newsgroups
  comp.infosystems.www.servers.unix or
  comp.infosystems.www.servers.ms-windows.

  Thanks for using the Apache HTTP Server, version 2.2.

                                     The Apache Software Foundation
                                     http://www.apache.org/
[root@localhost1 httpd-2.2.34]# ./configure --help
`configure' configures this package to adapt to many kinds of systems.

Usage: ./configure [OPTION]... [VAR=VALUE]...

To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE.  See below for descriptions of some of the useful variables.  #指定環境變量(例如,CC, CFLAGS…),指定它們爲。VAR =價值。如下是一些有用的變量的描述

Defaults for the options are specified in brackets.

Configuration:
  -h, --help              display this help and exit
      --help=short        display options specific to this package
      --help=recursive    display the short help of all the included packages
  -V, --version           display version information and exit
  -q, --quiet, --silent   do not print `checking ...' messages
      --cache-file=FILE   cache test results in FILE [disabled]
  -C, --config-cache      alias for `--cache-file=config.cache'
  -n, --no-create         do not create output files
      --srcdir=DIR        find the sources in DIR [configure dir or `..']

Installation directories:
  --prefix=PREFIX         install architecture-independent files in PREFIX  #指定安裝目錄,默認爲/usr/local/apache2
                          [/usr/local/apache2]
  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
                          [PREFIX]

By default, `make install' will install all the files in
`/usr/local/apache2/bin', `/usr/local/apache2/lib' etc.  You can specify
an installation prefix other than `/usr/local/apache2' using `--prefix',
for instance `--prefix=$HOME'.

For better control, use the options below.

Fine tuning of the installation directories:  #安裝目錄的微調 --bindir=DIR            user executables [EPREFIX/bin]    #用戶可執行文件 --sbindir=DIR           system admin executables [EPREFIX/sbin]
  --libexecdir=DIR        program executables [EPREFIX/libexec]
  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
  --libdir=DIR            object code libraries [EPREFIX/lib]
  --includedir=DIR        C header files [PREFIX/include]
  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
  --infodir=DIR           info documentation [DATAROOTDIR/info]
  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
  --mandir=DIR            man documentation [DATAROOTDIR/man]
  --docdir=DIR            documentation root [DATAROOTDIR/doc/PACKAGE]
  --htmldir=DIR           html documentation [DOCDIR]
  --dvidir=DIR            dvi documentation [DOCDIR]
  --pdfdir=DIR            pdf documentation [DOCDIR]
  --psdir=DIR             ps documentation [DOCDIR]

System types:
  --build=BUILD     configure for building on BUILD [guessed]
  --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  --target=TARGET   configure for building compilers for TARGET [HOST]

Optional Features:    #可選特性 --disable-option-checking  ignore unrecognized --enable/--with options  #忽略 unrecognized --enable/--with選項 --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)  #不包括FEATURE(和 --enale-FEATURE=no同樣) --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
  --enable-layout=LAYOUT
  --enable-v4-mapped      Allow IPv6 sockets to handle IPv4 connections  #容許IPv6處理IPv4鏈接 --enable-exception-hook Enable fatal exception hook
  --enable-maintainer-mode
                          Turn on debugging and compile time warnings    #打開調試而且編譯時警告 --enable-pie            Build httpd as a Position Independent Executable
  --enable-modules=MODULE-LIST
                          Space-separated list of modules to enable | "all" |
                          "most"
  --enable-mods-shared=MODULE-LIST
                          Space-separated list of shared modules to enable |
                          "all" | "most"
  --disable-authn-file    file-based authentication control
  --enable-authn-dbm      DBM-based authentication control
  --enable-authn-anon     anonymous user authentication control
  --enable-authn-dbd      SQL-based authentication control
  --disable-authn-default authentication backstopper
  --enable-authn-alias    auth provider alias
  --disable-authz-host    host-based authorization control
  --disable-authz-groupfile
                          'require group' authorization control
  --disable-authz-user    'require user' authorization control
  --enable-authz-dbm      DBM-based authorization control
  --enable-authz-owner    'require file-owner' authorization control
  --enable-authnz-ldap    LDAP based authentication
  --disable-authz-default authorization control backstopper
  --disable-auth-basic    basic authentication
  --enable-auth-digest    RFC2617 Digest authentication
  --enable-isapi          isapi extension support
  --enable-file-cache     File cache
  --enable-cache          dynamic file caching
  --enable-disk-cache     disk caching module
  --enable-mem-cache      memory caching module
  --enable-dbd            Apache DBD Framework
  --enable-bucketeer      buckets manipulation filter
  --enable-dumpio         I/O dump filter
  --enable-echo           ECHO server
  --enable-example        example and demo module
  --enable-case-filter    example uppercase conversion filter
  --enable-case-filter-in example uppercase conversion input filter
  --enable-reqtimeout     Limit time waiting for request from client
  --enable-ext-filter     external filter module
  --disable-include       Server Side Includes
  --disable-filter        Smart Filtering
  --enable-substitute     response content rewrite-like filtering
  --disable-charset-lite  character set translation
  --enable-charset-lite   character set translation
  --enable-deflate        Deflate transfer encoding support    #壓縮傳輸編碼的支持,提升傳輸速度,提高用戶訪問體驗
  --enable-ldap           LDAP caching and connection pooling services
  --disable-log-config    logging configuration
  --enable-log-forensic   forensic logging
  --enable-logio          input and output logging
  --disable-env           clearing/setting of ENV vars
  --enable-mime-magic     automagically determining MIME type
  --enable-cern-meta      CERN-type meta files
  --enable-expires        Expires header control    #EXPIRES頭部控制,激活容許經過配置文件控制HTTP的頭文件,即對網站的圖片等內容,提供在客戶端瀏覽器緩存的設置
  --enable-headers        HTTP header control    #HTTP的頭部控制
  --enable-ident          RFC 1413 identity check
  --enable-usertrack      user-session tracking
  --enable-unique-id      per-request unique ids
  --disable-setenvif      basing ENV vars on headers
  --disable-version       determining httpd version in config files
  --enable-proxy          Apache proxy module
  --enable-proxy-connect  Apache proxy CONNECT module
  --enable-proxy-ftp      Apache proxy FTP module
  --enable-proxy-http     Apache proxy HTTP module
  --enable-proxy-scgi     Apache proxy SCGI module
  --enable-proxy-ajp      Apache proxy AJP module
  --enable-proxy-balancer Apache proxy BALANCER module
  --enable-ssl            SSL/TLS support (mod_ssl)
  --enable-distcache      Select distcache support in mod_ssl
  --enable-optional-hook-export
                          example optional hook exporter
  --enable-optional-hook-import
                          example optional hook importer
  --enable-optional-fn-import
                          example optional function importer
  --enable-optional-fn-export
                          example optional function exporter
  --enable-static-support Build a statically linked version of the support
                          binaries
  --enable-static-htpasswd
                          Build a statically linked version of htpasswd
  --enable-static-htdigest
                          Build a statically linked version of htdigest
  --enable-static-rotatelogs
                          Build a statically linked version of rotatelogs
  --enable-static-logresolve
                          Build a statically linked version of logresolve
  --enable-static-htdbm   Build a statically linked version of htdbm
  --enable-static-ab      Build a statically linked version of ab
  --enable-static-checkgid
                          Build a statically linked version of checkgid
  --enable-static-htcacheclean
                          Build a statically linked version of htcacheclean
  --enable-static-httxt2dbm
                          Build a statically linked version of httxt2dbm
  --enable-http           HTTP protocol handling
  --disable-mime          mapping of file-extension to MIME
  --enable-dav            WebDAV protocol handling
  --disable-status        process/thread monitoring
  --disable-autoindex     directory listing
  --disable-asis          as-is filetypes
  --enable-info           server information
  --enable-suexec         set uid and gid for spawned processes
  --disable-cgid          CGI scripts
  --enable-cgi            CGI scripts
  --disable-cgi           CGI scripts
  --enable-cgid           CGI scripts
  --enable-dav-fs         DAV provider for the filesystem
  --enable-dav-lock       DAV provider for generic locking
  --enable-vhost-alias    mass virtual hosting module
  --disable-negotiation   content negotiation
  --disable-dir           directory request handling
  --enable-imagemap       server-side imagemaps
  --disable-actions       Action triggering on requests
  --enable-speling        correct common URL misspellings
  --disable-userdir       mapping of requests to user-specific directories
  --disable-alias         mapping of requests to different filesystem parts
  --enable-rewrite        rule based URL manipulation  #提供基於URL規則的重寫功能,根據已知URL地址,轉換其餘要訪問的URL地址
  --enable-so DSO capability  #DSO的能力,即在之後億DSO的方式編譯安裝共享模塊

Optional Packages:
  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  --with-included-apr     Use bundled copies of APR/APR-Util
  --with-apr=PATH         prefix for installed APR or the full path to
                             apr-config
  --with-apr-util=PATH    prefix for installed APU or the full path to
                             apu-config
  --with-pcre=PATH        Use external PCRE library
  --with-port=PORT        Port on which to listen (default is 80)
  --with-sslport=SSLPORT  Port on which to securelisten (default is 443)
  --with-z=DIR            use a specific zlib library
  --with-sslc=DIR         RSA SSL-C SSL/TLS toolkit
  --with-ssl=DIR          OpenSSL SSL/TLS toolkit
  --with-mpm=MPM          Choose the process model for Apache to use.
                          MPM={beos|event|worker|prefork|mpmt_os2|winnt}  #選擇用於Apache的模式,生產模式用worker,此模式原理是更多使用線程來處理請求
  --with-module=module-type:module-file
                          Enable module-file in the modules/<module-type>
                          directory.                #容許多少模塊在編譯中
  --with-program-name     alternate executable name
  --with-suexec-bin       Path to suexec binary
  --with-suexec-caller    User allowed to call SuExec
  --with-suexec-userdir   User subdirectory
  --with-suexec-docroot   SuExec root directory
  --with-suexec-uidmin    Minimal allowed UID
  --with-suexec-gidmin    Minimal allowed GID
  --with-suexec-logfile   Set the logfile
  --with-suexec-safepath  Set the safepath
  --with-suexec-umask     umask for suexec'd process

Some influential environment variables:
  CC          C compiler command
  CFLAGS      C compiler flags
  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
              nonstandard directory <lib dir>
  LIBS        libraries to pass to the linker, e.g. -l<library>
  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
              you have headers in a nonstandard directory <include dir>
  CPP         C preprocessor

Use these variables to override the choices made by `configure' or to help
it to find libraries and programs with nonstandard names/locations.

Report bugs to the package provider.

二、apache依賴組件安裝

[root@localhost1 httpd-2.2.34]# yum install gcc* zlib* -y
[root@localhost1 opt]# ./configure --prefix=/opt/apache2.2.34 --enable-deflate --enable-expires --enable-headers --enable-modules=most --enable-so --with-mpm=worker --enable-rewrite
[root@localhost1 opt]# make & make install
[root@localhost1 opt]# cd /opt/
[root@localhost1 opt]# ls
apache2.2.34
[root@localhost1 opt]# ln -s apache2.2.34/ apache/
ln: target `apache/' is not a directory: No such file or directory
[root@localhost1 opt]# ln -s apache2.2.34/ apache
[root@localhost1 opt]# ls
apache  apache2.2.34

啓動服務:apache

[root@localhost1 opt]# /opt/apache/bin/apachectl start
httpd: apr_sockaddr_info_get() failed for localhost1
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
服務啓動成功,但因爲沒有DNS出現這種提示,解決辦法以下
  [root@localhost1 conf]# vim /opt/apache/conf/httpd.conf ^C

ServerName www.example.com:80==========>localhost:80(192.168.1.2:80) 

[root@localhost1 conf]# /opt/apache/bin/apachectl graceful

It works!表示配置成功。

三、Apache重要目錄

[root@localhost1 apache]# ll
total 60
drwxr-xr-x  2 root root  4096 Feb 26 17:10 bin  #apche命令的目錄,如服務啓動命令
drwxr-xr-x  2 root root  4096 Feb 26 17:10 build
drwxr-xr-x  2 root root  4096 Feb 26 17:10 cgi-bin
drwxr-xr-x  4 root root  4096 Feb 26 17:33 conf
drwxr-xr-x  3 root root  4096 Feb 26 17:10 error
drwxr-xr-x  2 root root  4096 Jul  6  2017 htdocs  默認站點目錄
drwxr-xr-x  3 root root  4096 Feb 26 17:10 icons
drwxr-xr-x  2 root root  4096 Feb 26 17:10 include
drwxr-xr-x  3 root root  4096 Feb 26 17:10 lib
drwxr-xr-x  2 root root  4096 Feb 26 17:33 logs  日誌目錄
drwxr-xr-x  4 root root  4096 Feb 26 17:10 man
drwxr-xr-x 14 root root 12288 Jul  6  2017 manual
drwxr-xr-x  2 root root  4096 Feb 26 17:10 modules  apache的模塊目錄,一些程序通過編譯後都存放在這裏

(1)

[root@localhost1 apache]# tree -l 1 bin/
1 [error opening dir]
bin/
├── ab    HTTP服務器性能測試工具
├── apachectl  服務的啓動命令,一樣它也是一個腳本
├── apr-1-config
├── apu-1-config
├── apxs    是一個爲HTTP服務器編譯和安裝擴展模塊的工具
├── checkgid
├── dbmmanage
├── envvars
├── envvars-std
├── htcacheclean  這是清理磁盤緩衝區的命令,須要在編譯時指定相關的參數,不多使用
├── htdbm
├── htdigest
├── htpasswd  創建和更新基本認證文件,後面配置監控服務會用到
├── httpd  是apache的控制命令程序,apachectl執行時會調用httpd
├── httxt2dbm
├── logresolve
└── rotatelogs  apache自帶的日誌輪訓命令

0 directories, 17 files

(2)

[root@localhost1 apache]# tree -L 1 conf/
conf/
├── extra  apache額外的配置文件目錄,實際生產環境中常用或修改,如httpd-vhosts.conf默認在此
├── httpd.conf  主配置文件
├── magic
├── mime.types
└── original

2 directories, 3 files

(3)

[root@localhost1 apache]# tree -L 1 htdocs/
htdocs/
└── index.html

0 directories, 1 file

[root@localhost1 htdocs]# cat index.html
<html><body><h1>It works!</h1></body></html>

(4)

[root@localhost1 apache]# tree -L 1 logs/
logs/
├── access_log  默認訪問日誌目錄
├── cgisock.27892
├── error_log  錯誤日誌文件,服務啓動故障或其餘問題,均可以查看此文件
└── httpd.pid

0 directories, 4 files

主配置文件:

[root@localhost1 conf]# egrep -v "^.*#|^$" httpd.conf |nl
     1    ServerRoot "/opt/apache2.2.34"  #apache根目錄,只能root訪問,通常不作修改
     2    Listen 80  apache監聽端口,默認爲80端口
     3    <IfModule !mpm_netware_module>
     4    <IfModule !mpm_winnt_module>
     5    User daemon  apache的用戶,默認是daemon,實際生產環境建議修改
     6    Group daemon
     7    </IfModule>
     8    </IfModule>
     9    ServerAdmin you@example.com  系統管理員的郵箱,實際生產環境中修改成管理郵箱,有故障可直接發送至郵箱
    10    ServerName localhost:80(192.168.181.128:80)
    11    DocumentRoot "/opt/apache2.2.34/htdocs"
    12    <Directory />  禁止訪問文件系統所在的目錄
    13        Options FollowSymLinks
    14        AllowOverride None  禁止用戶對目錄配置文件進行修改
    15        Order deny,allow
    16        Deny from all
    17    </Directory>
    18    <Directory "/opt/apache2.2.34/htdocs">  apache默認網站站點目錄路徑
    19        Options Indexes FollowSymLinks
    20        AllowOverride None
    21        Order allow,deny
    22        Allow from all
    23    </Directory>
    24    <IfModule dir_module>
    25        DirectoryIndex index.html配置的默認首頁文件,如虛擬機沒有設置,默認就調用這裏的配置,首頁文件能夠有多個,每一個文件用空格分開,調用時,前面的優先匹配
    26    </IfModule>
    27    <FilesMatch "^\.ht">  防止.htaccess和.htpasswd等隱藏文件被Web用戶查看
    28        Order allow,deny
    29        Deny from all
    30        Satisfy All
    31    </FilesMatch>
    32    ErrorLog "logs/error_log"  錯誤日誌路徑
    33    LogLevel warn
    34    <IfModule log_config_module>
    35        LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    36        LogFormat "%h %l %u %t \"%r\" %>s %b" common
    37        <IfModule logio_module>
    38          LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    39        </IfModule>
    40        CustomLog "logs/access_log" common
    41    </IfModule>
    42    <IfModule alias_module>
    43        ScriptAlias /cgi-bin/ "/opt/apache2.2.34/cgi-bin/"
    44    </IfModule>
    45    <IfModule cgid_module>
    46    </IfModule>
    47    <Directory "/opt/apache2.2.34/cgi-bin">
    48        AllowOverride None
    49        Options None
    50        Order allow,deny
    51        Allow from all
    52    </Directory>
    53    DefaultType text/plain
    54    <IfModule headers_module>
    55        RequestHeader unset Proxy early
    56    </IfModule>
    57    <IfModule mime_module>
    58        TypesConfig conf/mime.types
    59        AddType application/x-compress .Z
    60        AddType application/x-gzip .gz .tgz
    61    </IfModule>
    62    <IfModule ssl_module>
    63    SSLRandomSeed startup builtin
    64    SSLRandomSeed connect builtin
    65    </IfModule>

Apache擴展的配置文件

Apache擴展的配置文件是經過httpd.conf主配置文件中嵌入Include命令來實現,不過默認狀況下是這樣:

# Virtual hosts
#Include conf/extra/httpd-vhosts.conf

# Various default settings
#Include conf/extra/httpd-default.conf

去掉註釋,即加入擴展

使用tree列出apache擴展的配置文件全部目錄的配置文件

[root@localhost1 conf]# tree -L 2 /opt/apache/conf/extra/
/opt/apache/conf/extra/
├── httpd-autoindex.conf
├── httpd-dav.conf  dav支持配置
├── httpd-default.conf  apache相關服務參數(超時時間、保持連續時間等)
├── httpd-info.conf
├── httpd-languages.conf  語言支持配置
├── httpd-manual.conf
├── httpd-mpm.conf  服務器池管理,也就是優化apache的一個配置文件
├── httpd-multilang-errordoc.conf
├── httpd-ssl.conf  提供apache ssl支持配配置文件
├── httpd-userdir.conf
└── httpd-vhosts.conf  虛擬主機的配置文件

0 directories, 11 files
[root@localhost1 conf]# cat extra/httpd-vhosts.conf 
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.  #若是你但願維護多個域名/主機名,你能夠爲她們設置虛擬主機容器。大部分只使用基於名稱的虛擬主機。
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80  80監聽端口

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/opt/apache2.2.34/docs/dummy-host.example.com"
    ServerName dummy-host.example.com  這裏配置提供的域名,生產環境須要把域名解析到服務器上,同時配置到外網IP上
    ServerAlias www.dummy-host.example.com  設置別名,此功能須要 apache mod_alias模塊支持
    ErrorLog "logs/dummy-host.example.com-error_log"  錯誤日誌目錄
    CustomLog "logs/dummy-host.example.com-access_log" common  日誌配置文件
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "/opt/apache2.2.34/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error_log"
    CustomLog "logs/dummy-host2.example.com-access_log" common
</VirtualHost>

查看apache編譯參數

[root@localhost1 conf]# cat /opt/apache/build/config.nice 
#! /bin/sh
#
# Created by configure

"./configure" \
"--prefix=/opt/apache2.2.34" \
"--enable-deflate" \
"--enable-expires" \
"--enable-headers" \
"--enable-modules=most" \
"--enable-so" \
"--with-mpm=worker" \
"--enable-rewrite" \
"$@"

 四、Apache服務基於域名的虛擬主機配置

開啓虛擬機功能

 

[root@localhost1 conf]# grep "httpd-vhosts.conf" /opt/apache/conf/httpd.conf 
Include conf/extra/httpd-vhosts.conf

 配置虛擬主機配置文件(httpd-vhosts.conf

 

[root@localhost1 extra]# cat httpd-vhosts.conf
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80  #這一行必定要去掉,否則會出錯,此文件只保留下面的配置文件

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin 928939638@qq.com
    DocumentRoot "/data/www/bbs"
    ServerName bbs.abc.com
    ServerAlias abc.com
    ErrorLog "logs/bbs-error_log"
    CustomLog "logs/bbs_access_log" common
</VirtualHost>

修改完成以後,在apache主配置文件中(httpd.conf)中加入虛擬機許可

修改windows本地hosts

錯誤總結:

配置了下虛擬主機,localhost打開發現錯誤:
    HTTP 錯誤 403 - 禁止訪問,即403 Forbidden:You don't have permission to access / on this server.

    多是權限不足引發的問題。

    解決方法:
    打開apache的配置文件httpd.conf,逐行檢查。
    找到:
 

代碼示例:
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all </Directory>
 
    因爲配置了php後,此處「Deny from all」爲拒絕一切鏈接。

    把此行修改成 「Allow from all」,便可解決問題。

    修改後的代碼爲:
 

代碼示例:
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    allow from all </Directory>
 
    瀏覽器裏打開http://localhost,問題解決。

總結:
在apache服務器中,遇到403禁止訪問時,重點關注下apache的httpd.conf配置文件中,是否有「Deny from all」這樣的代碼。
這個多是修改了某些配置文件後,重啓apache,被自動更改的。

附,另一個apache 403錯誤的例子。

apache 403錯誤,顯示信息以下:
您無權查看該網頁
您可能沒有權限用您提供的憑據查看此目錄或網頁
若是您確信可以查看該目錄或網頁,請嘗試使用 192.168.1.5 主頁上所列的電子郵件地址或電話與網站聯繫。
能夠單擊搜索,尋找 Internet 上的信息。

HTTP 錯誤 403 - 禁止訪問 
Internet Explorer

去掉顯示友好信息的鉤後顯示Forbidden   You don't have permission to access \ on this server.
檢查了一遍配置文件httpd.conf,找到這麼一段:
 

代碼示例:
<Directory />
     Options FollowSymLinks
     AllowOverride None
     Order deny,allow
     deny from all
     Satisfy all
</Directory>
 
而後試着把deny from all中的deny改爲了allow,保存後重起了apache,訪問測試網站徹底正常了。
APACHE升級到2.2版本以後,提供和支持很多模塊的支持,性能和安全上也有很多改進。
之前配置好apache的httpd.conf以後,便可使用。
但如今必須額外對這個文件進行其餘方面的配置,否則會出現 http 403權限問題錯誤。

解決方法。
如下爲httpd.conf文件的其中一段原代碼。
把下面代碼紅色標誌進行更改:
 

代碼示例:
<Directory "E:/wamp/www">
    #
    # 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
    # [url]http://httpd.apache.org/docs/2.2/mod/core.html#options[/url]
    # 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 all
    #
    # Controls who can get stuff from this server.
    #
#   onlineoffline tag - don't remove
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Directory>
 
紅色部分更改成 Allow from all ,也就是全部訪問容許經過。
http://blog.csdn.net/u011130583/article/details/42363831

五、基於端口的虛擬主機配置

實際生產環境中有不少是基於域名的虛擬主機,有不少引用場景:公司內網(如網站後臺界面、其餘發佈類的頁面)都是基於端口的虛擬配置。

默認狀況http默認監聽80端口,因此配置基於端口的主機,就是想應的增長監聽端口

 

[root@localhost1 ~]# cat /opt/apache/conf/extra/httpd-vhosts.conf | grep -v "#"


<VirtualHost 192.168.181.128:8888>
    ServerAdmin 928939638@qq.com
    DocumentRoot "/data/www/bbs"
    ServerName 192.168.181.1
    ServerAlias abc.com
    ErrorLog "logs/bbs-error_log"
    CustomLog "logs/bbs-access_log" common
</VirtualHost>

<VirtualHost 192.168.181.128:9999>
    ServerAdmin 928939638@qq.com
    DocumentRoot "/data/www/blog"
    ServerName 192.168.181.2
    ServerAlias abc.com
    ErrorLog "logs/bbs-error_log"
    CustomLog "logs/bbs-access_log" common
</VirtualHost>
[root@localhost1 ~]# cat /opt/apache/conf/httpd.conf | grep -v "#"

ServerRoot "/opt/apache2.2.34"

Listen 80
Listen 8888
Listen 9999


<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
User daemon
Group daemon

</IfModule>
</IfModule>


ServerAdmin you@example.com

ServerName 192.168.181.128:80

DocumentRoot "/opt/apache2.2.34/htdocs"

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
</Directory>


<Directory "/opt/apache2.2.34/htdocs">
    Options -Indexes FollowSymLinks

    AllowOverride None

    Order allow,deny
    Allow from all

</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<FilesMatch "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</FilesMatch>

ErrorLog "logs/error_log"

LogLevel warn

<IfModule log_config_module>
    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>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access_log" common

</IfModule>

<IfModule alias_module>


    ScriptAlias /cgi-bin/ "/opt/apache2.2.34/cgi-bin/"

</IfModule>

<IfModule cgid_module>
</IfModule>

<Directory "/opt/apache2.2.34/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

DefaultType text/plain

<IfModule headers_module>
    RequestHeader unset Proxy early
</IfModule>

<IfModule mime_module>
    TypesConfig conf/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz



</IfModule>






Include conf/extra/httpd-mpm.conf





 Include conf/extra/httpd-vhosts.conf




<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

<Directory "/data/www/bbs">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

<Directory "/data/www/blog">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
[root@localhost1 ~]# cat /data/www/bbs/index.html 
this is a bbs page
[root@localhost1 ~]# cat /data/www/blog/index.html 
this is blog page

[root@localhost1 ~]# cat /opt/apache/conf/extra/httpd-vhosts.conf | grep -v "#"


<VirtualHost *:8888>
    ServerAdmin 928939638@qq.com
    DocumentRoot "/data/www/bbs"
    ServerName bbs.abc.com
    ServerAlias abc.com
    ErrorLog "logs/bbs-error_log"
    CustomLog "logs/bbs-access_log" common
</VirtualHost>

<VirtualHost *:9999>
    ServerAdmin 928939638@qq.com
    DocumentRoot "/data/www/blog"
    ServerName blog.abc.com
    ServerAlias abc.com
    ErrorLog "logs/bbs-error_log"
    CustomLog "logs/bbs-access_log" common
</VirtualHost>

六、Apache服務mod_expires緩存模塊

簡介:

  此模塊是容許經過Apache配置文件控制HTTP的「expires」和「cache-control」頭的內容,用於控制服務器應答時的「expires」頭的內容和「cache-control」頭的max-age的指令,這個有效期能夠設置爲對於源文件最後的修改時間或客戶端訪問的時間

  這些HTTP頭向客戶端代表了內容的有效性和持久性,若是客戶端本地有緩存,則用戶再次訪問時讀取的內容就是從緩存裏讀取的(緩存沒有失效的狀況下)而不是從服務器端讀取的,客戶端還會檢查緩存中的內容,看看是否是須要從服務器端進行更新,從而增長用戶的體驗度,減小服務器的壓力,實際生產環境中也是重要的調優參數之一。

(1)檢查與安裝模塊

具體編譯命令以下
[root@Centos httpd-2.4.23]# ./configure\
--enable-expires
以 DSO 的方式編譯安裝以下
cd /Downloads/tools/httpd2.2.24/modules/metadata/
/application/apache/bin/apxs -c -i -a mod_expires.c
參數說明
-a 此選項會自動增長一個 LoadModule 行到 httpd.conf 文件中,來激活模塊,若是此行已存在,則啓用
-c 此選項表示須要執行編譯操做
-i 此選項表示須要執行安裝操做,以安裝一個或多個動態共享對象到服務器 modules 目錄中
[root@Centos modules]# cd /Downloads/tools/httpd-2.4.23/modules/metadata/
[root@Centos metadata]# /application/apache/bin/apxs -a -c -i mod_expires.c
處程省略
----------------------------------------------------------------------
chmod 755 /application/apache2.4.23/modules/mod_expires.so
[activating module `expires' in /application/apache2.4.23/conf/httpd.conf]

檢查當前的http headers信息

[root@localhost1 httpd-2.2.34]# curl -I http://bbs.abc.com:8888/
HTTP/1.1 200 OK
Date: Tue, 27 Feb 2018 05:14:26 GMT
Server: Apache/2.2.34 (Unix) DAV/2
Last-Modified: Tue, 27 Feb 2018 01:19:12 GMT
ETag: "a059e-13-566276a119d53"
Accept-Ranges: bytes
Content-Length: 19
Content-Type: text/html

(2)配置模塊

配置模塊有兩種模式:主配置裏面配置與單個虛擬主機配置文件裏配置

配置HTTP主配置文件以下

[root@localhost1 httpd-2.2.34]# vim /opt/apache/conf/httpd.conf
[root@localhost1 httpd-2.2.34]# tail -10 /opt/apache/conf/httpd.conf
ExpiresActive on
    ExpiresDefault "access plus 12 month"
    ExpiresByType text/css "access plus 12 month"
    ExpiresByType image/gif "access plus 12 month"
    ExpiresByType image/jpge "access plus 12 month"
    ExpiresByType image/jpg "access plus 12 month"
    ExpiresByType image/png "access plus 12 month"
    ExpiresByType application/x-shockwave-flash "access plus 12 month"
    ExpiresByType application/x-javascript "access plus 12 month"
    ExpiresByType video/x-flv "access plus 12 month"
[root@localhost1 httpd-2.2.34]# tail -20 /opt/apache/conf/httpd.conf
    Allow from all
</Directory>

<Directory "/data/www/blog">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

ExpiresActive on
    ExpiresDefault "access plus 12 month"
    ExpiresByType text/css "access plus 12 month"
    ExpiresByType image/gif "access plus 12 month"
    ExpiresByType image/jpge "access plus 12 month"
    ExpiresByType image/jpg "access plus 12 month"
    ExpiresByType image/png "access plus 12 month"
    ExpiresByType application/x-shockwave-flash "access plus 12 month"
    ExpiresByType application/x-javascript "access plus 12 month"
    ExpiresByType video/x-flv "access plus 12 month"

[root@localhost1 bbs]# curl -I http://bbs.abc.com:8888/
HTTP/1.1 200 OK
Date: Tue, 27 Feb 2018 05:25:29 GMT
Server: Apache/2.2.34 (Unix) DAV/2
Last-Modified: Tue, 27 Feb 2018 01:19:12 GMT
ETag: "a059e-13-566276a119d53"
Accept-Ranges: bytes
Content-Length: 19
Cache-Control: max-age=31104000
Expires: Fri, 22 Feb 2019 05:25:29 GMT
Content-Type: text/html

說明若是配置HTTP主配置文件,則全局生效,虛擬主機配置文件則不須要配置

配置單個虛擬主機文件以下:

<VirtualHost *:9999>
ServerAdmin admini@abc.com
DocumentRoot "/data/www/blog"
ServerName blog.abc.com
ServerAlias blog1.com
ErrorLog "logs/bbs-error_log"
CustomLog "logs/bbs-access_log" common
ExpiresActive on
ExpiresDefault "access plus 12 month"
ExpiresByType text/css "access plus 12 month"
ExpiresByType image/gif "access plus 12 month"
ExpiresByType image/jpge "access plus 12 month"
ExpiresByType image/jpg "access plus 12 month"
ExpiresByType image/png "access plus 12 month"
ExpiresByType application/x-shockwave-flash "access plus 12 month"
ExpiresByType application/x-javascript "access plus 12 month"
ExpiresByType video/x-flv "access plus 12 month"

(3)mod_expires模塊的優勢:

  提高用戶對網站的體驗度:因爲一些文件緩存在本地,訪問速度提高了,用戶體驗也就提高了

  減小服務器帶寬與負載壓力:因爲用戶訪問時時讀取本地緩存的文件內容,減小了與服務器之間的交互,從而減小了服務器的壓力

  節約維護服務器成本:和上述同樣,服務器壓力小了,維護人員也會相應的減小,服務器配件配置更新的速度也會相應的慢下來

  注:這個緩存也會有失效的時候就是用戶主動清空瀏覽器緩存或者有效期過時

七、Apache的mod_deflate壓縮模塊

簡介:

  此壓縮模塊提供了DEFLATE輸出過濾器,容許服務器將內容發送給客戶端以前進行壓縮,節省帶寬資源

[root@localhost1 bbs]# /opt/apache/bin/apachectl -l | grep 'deflate'
  mod_deflate.c
[root@localhost1 bbs]# curl -I http://bbs.abc.com:8888/
HTTP/1.1 200 OK
Date: Tue, 27 Feb 2018 05:40:50 GMT
Server: Apache/2.2.34 (Unix) DAV/2
Last-Modified: Tue, 27 Feb 2018 01:19:12 GMT
ETag: "a059e-13-566276a119d53"
Accept-Ranges: bytes
Content-Length: 19
Cache-Control: max-age=31104000
Expires: Fri, 22 Feb 2019 05:40:50 GMT
Content-Type: text/html
[root@localhost1 bbs]# vim /opt/apache/conf/httpd.conf
[root@localhost1 bbs]# tail -20 /opt/apache/conf/httpd.conf
</Directory>

ExpiresActive on
    ExpiresDefault "access plus 12 month"
    ExpiresByType text/css "access plus 12 month"
    ExpiresByType image/gif "access plus 12 month"
    ExpiresByType image/jpge "access plus 12 month"
    ExpiresByType image/jpg "access plus 12 month"
    ExpiresByType image/png "access plus 12 month"
    ExpiresByType application/x-shockwave-flash "access plus 12 month"
    ExpiresByType application/x-javascript "access plus 12 month"
    ExpiresByType video/x-flv "access plus 12 month"

<IfModule mod_deflate.c>
    DeflateCompressionLevel 9
    SetOutputFilter DEFLATE
    AddOutputFilterByType DEFLATE text/html text/plain /text/xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/css
</IfModule>
[root@localhost1 bbs]# /opt/apache/bin/apachectl -t
Syntax OK
[root@localhost1 bbs]# /opt/apache/bin/apachectl graceful
[root@localhost1 bbs]# lsof -i tcp:8888
COMMAND   PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
httpd   27892   root    6w  IPv6  63602      0t0  TCP *:ddi-tcp-1 (LISTEN)
httpd   45450 daemon    6u  IPv6  63602      0t0  TCP *:ddi-tcp-1 (LISTEN)
httpd   45451 daemon    6u  IPv6  63602      0t0  TCP *:ddi-tcp-1 (LISTEN)
[root@localhost1 bbs]# curl -I http://bbs.abc.com:8888/1.jpg
HTTP/1.1 200 OK
Date: Tue, 27 Feb 2018 05:45:08 GMT
Server: Apache/2.2.34 (Unix) DAV/2
Last-Modified: Wed, 29 Nov 2017 08:16:39 GMT
ETag: "a059a-bdb1-55f1ac137c7c0"
Accept-Ranges: bytes
Content-Length: 48561
Cache-Control: max-age=31104000
Expires: Fri, 22 Feb 2019 05:45:08 GMT
Vary: Accept-Encoding    #出現這個提示代表已經啓用壓縮
Content-Type: image/jpeg

八、Apache服務日誌輪詢配置(安裝配置cronolog)

Apache服務安裝後,默認有本身的日誌服務,如今通常生產環境不太經常使用默認的日誌服務

默認日誌服務以下

[root@localhost1 bin]# ll
total 3776
-rwxr-xr-x 1 root root   75861 Feb 26 17:10 ab
-rwxr-xr-x 1 root root    3425 Feb 26 17:08 apachectl
-rwxr-xr-x 1 root root    6986 Feb 26 17:10 apr-1-config
-rwxr-xr-x 1 root root    6601 Feb 26 17:10 apu-1-config
-rwxr-xr-x 1 root root   22652 Feb 26 17:08 apxs
-rwxr-xr-x 1 root root   12269 Feb 26 17:10 checkgid
-rwxr-xr-x 1 root root    8925 Feb 26 17:08 dbmmanage
-rw-r--r-- 1 root root    1071 Feb 26 17:08 envvars
-rw-r--r-- 1 root root    1071 Feb 26 17:08 envvars-std
-rwxr-xr-x 1 root root   45328 Feb 26 17:10 htcacheclean
-rwxr-xr-x 1 root root   30347 Feb 26 17:10 htdbm
-rwxr-xr-x 1 root root   22476 Feb 26 17:10 htdigest
-rwxr-xr-x 1 root root   31665 Feb 26 17:10 htpasswd
-rwxr-xr-x 1 root root 3497167 Feb 26 17:10 httpd
-rwxr-xr-x 1 root root   20180 Feb 26 17:10 httxt2dbm
-rwxr-xr-x 1 root root   22937 Feb 26 17:10 logresolve
-rwxr-xr-x 1 root root   24964 Feb 26 17:10 rotatelogs  #默認日誌服務
查看服務安裝是否成功
[root@Centos cronolog-1.6.2]# ls /usr/local/sbin/
cronolog cronosplit
編輯主配置文件修改日誌配置
[root@Centos cronolog-1.6.2]# vi /application/apache/conf/extra/httpd-vhosts.conf
#port bash name
<VirtualHost *:80>
ServerAdmin admini@abc.com
DocumentRoot "/data/www/bbs"
ServerName bbs.abc.com
ServerAlias bbs.com
ErrorLog "logs/bbs-error_log"
#CustomLog "logs/bbs-access_log" common#註釋掉原來的配置,新增下面一行配置
CustomLog "|/usr/local/sbin/cronolog /application/apache/logs/bbs-access_%d.log" combined
#按天來輪詢日誌信息
"/application/apache2.4.23/conf/extra/httpd-vhosts.conf" 43L, 1397C written
檢查語法與重啓服務
[root@Centos cronolog-1.6.2]# /application/apache/bin/apachectl -t
Syntax OK
[root@Centos cronolog-1.6.2]# /application/apache/bin/apachectl graceful
1、 查看日誌信息
進入日誌記錄的目錄查看
[root@Centos cronolog-1.6.2]# cd /application/apache/logs/
[root@Centos logs]# ll
total 204
-rw-r--r--. 1 root root 3255 Sep 20 03:44 access_log
-rw-r--r--. 1 root root 68367 Sep 23 08:35 bbs-access_log
-rw-r--r--. 1 root root 79370 Sep 23 08:35 bbs-error_log
-rw-r--r--. 1 root root 2315 Sep 23 07:38 blog-access_log
-rw-r--r--. 1 root root 0 Sep 23 06:31 blog-error_log
-rw-r--r--. 1 root root 32632 Sep 23 08:52 error_log
-rw-r--r--. 1 root root 5 Sep 23 08:52 httpd.pid
上面是原來的日誌目錄內容,接下來咱們訪問站點看看目錄內容會不會有變化
249 / 753
[root@Centos logs]# ll
total 212
-rw-r--r--. 1 root root 3255 Sep 20 03:44 access_log
-rw-r--r--. 1 root root 1788 Sep 23 09:00 bbs-access_23.log
-rw-r--r--. 1 root root 68367 Sep 23 08:35 bbs-access_log
-rw-r--r--. 1 root root 81482 Sep 23 09:00 bbs-error_log
-rw-r--r--. 1 root root 2315 Sep 23 07:38 blog-access_log
-rw-r--r--. 1 root root 0 Sep 23 06:31 blog-error_log
-rw-r--r--. 1 root root 33503 Sep 23 09:00 error_log
-rw-r--r--. 1 root root 5 Sep 23 09:00 httpd.pid
代表配置是正確的,訪問站點後會自動生成以天爲單位的日誌文件
[root@Centos logs]# date -s '09/24/16'
Sat Sep 24 00:00:00 CST 2016
[root@Centos logs]# ll
total 220
-rw-r--r--. 1 root root 3255 Sep 20 03:44 access_log
-rw-r--r--. 1 root root 1788 Sep 23 09:00 bbs-access_23.log
-rw-r--r--. 1 root root 894 Sep 24 00:00 bbs-access_24.log
-rw-r--r--. 1 root root 68367 Sep 23 08:35 bbs-access_log
-rw-r--r--. 1 root root 82538 Sep 24 00:00 bbs-error_log
-rw-r--r--. 1 root root 2315 Sep 23 07:38 blog-access_log
-rw-r--r--. 1 root root 0 Sep 23 06:31 blog-error_log
-rw-r--r--. 1 root root 33503 Sep 23 09:00 error_log
-rw-r--r--. 1 root root 5 Sep 23 09:00 httpd.pid
修改時間後,目錄會自動生產一個日誌文件
2、 日誌記錄的信息
[root@Centos logs]# tail -f /application/apache/logs/bbs-access_24.log
192.168.1.200 - - [24/Sep/2016:00:00:18 +0800] "GET / HTTP/1.1" 403 209 "-" "Mozilla/5.0 (compatible;
MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
192.168.1.200 - - [24/Sep/2016:00:00:19 +0800] "GET / HTTP/1.1" 403 209 "-" "Mozilla/5.0 (compatible;
MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
目前是六行信息,咱們在客戶端刷新網頁看看變化
[root@Centos logs]# tail -f /application/apache/logs/bbs-access_24.log
192.168.1.200 - - [24/Sep/2016:00:00:18 +0800] "GET / HTTP/1.1" 403 209 "-" "Mozilla/5.0 (compatible;
MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
250 / 753
192.168.1.200 - - [24/Sep/2016:00:00:19 +0800] "GET / HTTP/1.1" 403 209 "-" "Mozilla/5.0 (compatible;
MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
192.168.1.200 - - [24/Sep/2016:00:14:02 +0800] "GET / HTTP/1.1" 403 209 "-" "Mozilla/5.0 (compatible;
MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
192.168.1.200 - - [24/Sep/2016:00:14:05 +0800] "GET / HTTP/1.1" 403 209 "-" "Mozilla/5.0 (compatible;
MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
刷新兩次就會增長兩行的日誌記錄,信息裏說明有:客戶端地址、訪問時間、協議、客戶端系統版本、瀏覽器

九、Apache服務優化配置

(1)修改默認配置用戶

Apache默認用戶是deamon

[root@localhost1 logs]# egrep "User|Group" /opt/apache/conf/httpd.conf
# User/Group: The name (or #number) of the user/group to run httpd as.
User apache
Group apache
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
# User home directories

(2)錯誤頁面修改

[root@Centos ~]# grep "Error" /application/apache/conf/httpd.conf
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
ErrorLog "logs/error_log"
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html # ErrorDocument 404 http://www.abc.com 跳轉到指定頁面
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html:

(3)使用worker模式

編譯安裝時已經使用worker模式,提升併發

(4)屏蔽Apache版本信息

修改 httpd.conf 文件,打開模塊
[root@Centos conf]# cat /application/apache/conf/httpd.conf|grep httpd-default
#Include conf/extra/httpd-default.conf
修改爲 Include conf/extra/httpd-default.conf
[root@Centos conf]# sed -i 's#\#Include conf/extra/httpd-default.conf#Include conf/extra/httpd-default.conf#g'
//application/apache/conf/httpd.conf
[root@Centos conf]# cat /application/apache/conf/httpd.conf|grep httpd-default
Include conf/extra/httpd-default.conf
[root@Centos conf]# ../bin/apachectl -t
Syntax OK
[root@Centos conf]# ../bin/apachectl graceful
[root@Centos apache]# egrep -v "^.*#|^$" ./conf/extra/httpd-default.conf
Timeout 60
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
UseCanonicalName Off
AccessFileName .htaccess
ServerTokens Full-----------------------------------------------> ServerTokens Prod
ServerSignature On---------------------------------------------> ServerSignature Off
HostnameLookups Off
<IfModule reqtimeout_module>
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
</IfModule>

(5)禁止目錄瀏覽權限

</IfModule>
<Directory "/data/www/blog">
Options Indexes FollowSymLinks #修改爲 OptionsFollowSymLinks
AllowOverride None
Require all granted
</Directory>

(6)禁止用戶覆蓋(重載)

</IfModule>
<Directory "/data/www/blog">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

(7)開啓Apache防盜鏈功能

此功能是爲了其它用戶使用站點中的文件,可是不是下載到本地而後上傳到 B 網站,而是直接使用文件的連接,
因此當別的用戶訪問這個連接時,其實真正訪問的不是 B 網站,而是咱們的站點服務器,一旦這種流量增長,
就會增長服務器的負載,因此這也是優化的重要參數之一
首先在/application/apache/conf/httpd.conf 文件裏打開以下模塊
LoadModule rewrite_module modules/mod_rewrite.so
<IfModule rewrite_module >
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://www.abc.com.org/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.abc.com.org$ [NC]
RewriteCond %{HTTP_REFERER} !^ abc.com.org/.*$ [NC]
</IfModule>
優化的參數太多,具體應用還得實際生產環境的需求

(8)禁止PHP解析指定站點的目錄

<Directory "/data/www/blog">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
php_flag engine off #防止上傳 PHP 木馬文件,遠程執行
</Directory>
相關文章
相關標籤/搜索