KEMBAR78
U2 ApacheServer Slides v1 | PDF | Apache Http Server | Domain Name System
0% found this document useful (0 votes)
3 views44 pages

U2 ApacheServer Slides v1

The document provides a comprehensive guide on managing the Apache web server, covering installation, configuration files, modules, directives, and virtual hosts. It details commands for installation, testing, and managing modules, as well as the structure and purpose of various configuration files in both Linux and Windows environments. Additionally, it explains the context and application order of directives, along with specific examples for configuring virtual hosts and handling errors.

Uploaded by

Juan M.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

U2 ApacheServer Slides v1

The document provides a comprehensive guide on managing the Apache web server, covering installation, configuration files, modules, directives, and virtual hosts. It details commands for installation, testing, and managing modules, as well as the structure and purpose of various configuration files in both Linux and Windows environments. Additionally, it explains the context and application order of directives, along with specific examples for configuring virtual hosts and handling errors.

Uploaded by

Juan M.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Web server management: Apache

1. Apache installation
2. Apache modules
3. Apache configuration files
4. Apache directives context
5. Virtual hosts
6. Apache directives
7. .htaccess files
8. More container directives

Mercedes Rodríguez, José Ramón Rodríguez (2024)


Apache management
Apache installation
• Apache is a HTTP server.
• Documentation: http://httpd.apache.org/docs/current/
• Configuration through directives:
http://httpd.apache.org/docs/current/mod/quickreference.html
• Apache’s installation:
▪ sudo apt install apache2
• To test the installation, URL in the browser => http://localhost
• To start/restart/stop/status Apache:
▪ sudo apache2ctl start|restart|graceful|stop|
graceful-stop|status
• sudo service start apache2.service
• To test the configuration files' syntax without starting Apache:
▪ sudo apache2ctl configtest
▪ sudo apache2ctl -t

2
Apache management
Apache module installation
• Apache is modular: directives are packed in modules.
▪ http://httpd.apache.org/docs/current/mod/
• Essential modules are loaded in Apache's bootup: core+base.
• Modules can be installed/uninstalled:
▪ sudo a2enmod module_name
▪ sudo a2dismod module_name
• Module’s loading file: /etc/apache2/mods-available/*.load
• Module’s configuration file: /etc/apache2/mods-available/*.conf
• Modules info
• Examples:
▪ Install the modules mod_info, mod_userdir, mod_ldap, mod_alias
▪ Install PHP in Linux and mod_php in Apache:
− sudo apt install php libapache2-mod-php
− sudo a2enmod php7.4
3
Apache management
Apache modules status and info
• mod_status: gives the current server statistics in an easily
readable form.
• mod_info: provides a comprehensive overview of the server
configuration.
# mod_status # mod_info
<Location /server-status> <Location /server-info>
SetHandler server-status SetHandler server-info
Require local Require ip 127.0.0.1
Require ip 192.168.2.63 Require ip 10.0/16
</Location> </Location>

• To access server statistics


▪ => URL: http://your.server.name/server-status
• To access the server information
▪ => URL: http://your.host.example.com/server-info

4
Apache management
Apache configuration files in Linux
• Directory: /etc/apache2
File Description
apache2.conf Main server configuration (global settings)
ports.conf Open ports for Apache
envvar Environmental variables for Apache
mods-available/ Modules that are available for activation
mods-enabled/ Loaded and activated modules in Apache
sites-available/ Virtual websites that are available for installation
sites-enabled/ Loaded and activated virtual websites in Apache
conf-available/ Other configuration files that are available for activation
conf-enabled/ Loaded and activated configuration files in Apache

5
Apache management
Apache configuration files in Windows
• Directories: conf and conf/extra, inside the server’s root directory
File Description
httpd.conf Main server configuration (global settings)
httpd-ajp.conf Apache Jserv protocol’s configuration
httpd-autoindex.conf Directivas for listing the files generated by the server
httpd-dav.conf Distributed authoring and versioning
httpd-default.conf Default setup for the HTTP server
httpd-info.conf Information about processed client’s requests by the server
httpd-languages.conf Language setup
httpd-manual.conf Local access to Apache documentation
http-mpm.conf Multiprocess modules’ configuration
httpd-multilang-errordoc.conf Multi-language error’s documents’ configuration
httpd-proxy.conf Apache proxy’s configuration
httpd-ssl.conf HTTPS server’s configuration
httpd-userdir.conf User personal website’s configuration
httpd-vhosts.conf Virtual hosts’ configuration
httpd-xampp.conf XAMPP settings in Apache
proxy-html.conf Proxy’s configuration example

6
Apache management
Apache directives context
• 4 contexts (scope) in Apache for directives:
– Server config (s): it may be used in the server configuration files,
but neither in containers nor in .htaccess files.
– Virtual host (v): inside <VirtualHost> containers.
– Directory (d): inside <Directory>, <Location>, <Files>, <If>,
and <Proxy> containers
– .htaccess files (h), distributed in the file system’s directories:
– .htaccess directives are processed depending on the value of
the attribute AllowOverride.
– The use of .htaccess files can be disabled completely
by AllowOverride None
– Proxy section (p): inside <Proxy> containers.
https://httpd.apache.org/docs/2.4/es/mod/quickreference.html
7
Web server management
Apache directives aplication order

1. The apache2.conf file is processed.


2. The text files in Include directives are included.
3. If a directive appears more than once, the last
appearance prevails.
4. The processed directives in the .htaccess files
(AllowOverride’s value) prevail over directives in
the main configuration file.

8
Apache management
Virtual hosts
Container <VirtualHost>
<VirtualHost addr[:port] ...> ... </VirtualHost>
• Each block defines a VirtualHost (VH):
▪ Each VH represents a website.
▪ Each VH block should be defined a .conf file in
/etc/apache2/sites-available
• To activate a listening {addr:port} in <VirtualHost>,
Apache must be listening on the correct addresses using
Listen.
• addr can be:
▪ The IP address of the virtual host
▪ A fully qualified domain (not recommended)
▪ The character *, to match all IP addresses
▪ _default_, to catch unmatched IP addresses.
9
Apache management
Virtual hosts’ considerations
• :port
▪ If unspecified then it defaults to the same port as the most
recent Listen directive in the main server.
▪ :* , matches all ports on that address (recommended
with _default_)
• Each <VirtualHost> block should have at least:
▪ A ServerName statement.
− If not, ServerName from the "main" server configuration will be
inherited.
▪ A DocumentRoot statement.

10
Apache management
Virtual hosts’ considerations
• VH documentation:
▪ Name-based vs. IP-based Virtual Hosts
▪ An In-Depth Discussion of Virtual Host Matching
• Name-based virtual hosting is a applied after the server has selected the
best matching IP.
• Do not care about what IP address the client has connected to, do use a
"*" as the address of every virtual host, and name-based virtual hosting is
applied across all configured virtual hosts.
• If no matching virtual host is found, then the first listed virtual host that
matches the IP address will be the default virtual host.
• Any port in the ”Host:” header field is never used during the matching
process. Apache always uses the real port to which the client sent the
request.

11
Apache management
Virtual hosts’ considerations
• If two vhosts have an address in common, those common addresses act as
name-based virtual hosts implicitly. This is new behavior as of 2.3.11.
• The main server is only used to serve a request if the IP address and port
number to which the client connected does not match any vhost
(including a * vhost). In other words, the main server only catches a
request for an unspecified address/port combination (unless there is
a _default_ vhost which matches that port).
• You should never specify DNS names in VirtualHost directives because it
will force your server to rely on DNS to boot. Furthermore it poses a
security threat if you do not control the DNS for all the domains listed.
• ServerName should always be set for each vhost. Otherwise a DNS lookup
is required for each vhost.

12
Apache management
Virtual hosts’ considerations
• Examples in documentation:
▪ https://httpd.apache.org/docs/2.4/es/vhosts/examples.
html
• To debug the virtual host configuration:
sudo apachectl -S
▪ Show the settings as parsed from the config file (currently
only shows the virtualhost settings).
• To enable/disable VH:
sudo a2ensite virtualhost-conf-file
sudo a2dissite virtualhost-conf-file

13
Apache management
Directives
Include and IncludeOptional
Include file-path|directory-path|wildcard
• Includes other configuration files from within the server
configuration files.
• Wildcard characters can be used in the filename or directory
parts of the path to include several files at once, in
alphabetical order.
• IncludeOptional: if wildcards are used and they do not match
any file or directory or if a file path does not exist on the file
system, it will be silently ignored (instead of causing an error).

14
Apache management
Directives. Directory
<Directory> (s,v)
<Directory directory-path> ... </Directory>
• Enclose a group of directives that apply only to the named
file-system directory, sub-directories, and their contents.
• Directory-path is either the full path to a directory, or a wild-
card string. Eg. <Directory /home/*/public_html> will match
/home/user/public_html
Regular expressions can also be used, with the addition of
the ~ character. For example:
• Eg. <Directory ~ "^/www/.*/[0-9]{3}">
would match directories in /www/ that consisted of three numbers.
The same as: <DirectoryMatch "^/www/.*/[0-9]{3}">

15
Apache management
Directives. Directory
<Directory> example:

# Group of directives applied to /opt/xampp/htdocs


# and subdirectories
<Directory "/opt/xampp/htdocs">
Options Indexes FollowSymLinks
DirectoryIndex index.html
AllowOverride none
</Directory>

16
Apache management
Directives
Listen (s)
Listen [IP-address:]portnumber [protocol]
• IP addresses and ports that the server listens to.
• If only a port number is specified, the server listens to the given
port on all interfaces.
• Examples:
Listen 80
Listen 192.170.2.5:8000
Listen [2001:db8::a00:20ff:fea7:ccea]:80
Listen 192.170.2.1:8443 https
ServerRoot (s)
ServerRoot directory-path
• Defaults to /etc/apache2
17
Apache management
Directives
ServerName (s,v)
ServerName [scheme://]domain-name|ip-
address[:port]
• It sets the request scheme, hostname and port that the
server uses to identify itself.
• Eg. ServerName www.webox.es
ServerAdmin (s,v)
ServerAdmin email-address|URL
• It sets the contact address that the server includes in any
error messages it returns to the client.

18
Apache management
Directives
ServerAlias (v)
• It sets the alternate names for a host. It may include
wildcards.
<VirtualHost *:80>
Eg. ServerName server.example.com
ServerAlias server server2.example.com server2
ServerAlias *.example.com
# ...
</VirtualHost>

19
Apache management
Directives

• DocumentRoot (s,v)
DocumentRoot directory-path
• Directory that forms the main document tree visible from the
web.
• The server appends the path from the requested URL to the
document root to make the path to the document.
• Eg. DocumentRoot "/usr/web"
▪ Access to
− URL http://my.example.com/index.html
▪ refers to the file
− /usr/web/index.html

20
Apache management
Directives
Alias (s,h)
Alias [URL-path] file-path|directory-path
• Maps URLs to filesystem locations. It allows documents to be stored in the
local filesystem other than under the DocumentRoot.
• If creating an Alias to a directory outside of the DocumentRoot, it may be
needed to explicitly permit access to the target directory.
• Eg.
Alias "/image" "/ftp/pub/image“
<Directory "/ftp/pub/image">
Require all granted
</Directory>

▪ A request for URL: http://example.com/image/foo.gif


▪ would cause the server to return the file: /ftp/pub/image/foo.gif

21
Apache management
Directives
Redirect (s,v,d,h)
Redirect [status] [URL-path] URL
• It maps an old URL into a new one by asking the client to refetch the
resource at the new location.
• The old URL-path is a case-sensitive path beginning with a slash. A relative
path is not allowed.
• The new URL may be either an absolute URL beginning with a scheme and
hostname, or a URL-path beginning with a slash. In this latter case the
scheme and hostname of the current server will be added.
• If no status argument is given, the redirect will be "temporary" (HTTP
status 302), ie. the resource has moved temporarily. The status argument
can be used to return other HTTP status codes:
– permanent: returns code 301, the resource has moved permanently
– temp: returns code 302 , temporary redirect status (default)
– seeother: returns code 303, the resource has been replaced
– gone: returns code 410, the resource has been permanently removed.
The URL argument should be omitted.

22
Apache management
Directives
• Redirect examples:
Redirect permanent "/one" http://example.com/two
Redirect 303 "/three" "http://example.com/other"

▪ In the next example, if the client requests


http://example.com/service/foo.txt, it will be told to
access http://foo2.example.com/service/foo.txt instead.
# Redirect to a URL on a different host
Redirect "/service" http://foo2.example.com/service
# Redirect to a URL on the same host
Redirect "/one" "/two"

23
Apache management
Directives
ErrorDocument (s,v,d,h)
ErrorDocument error-code document
• What the server will return to the client in case of an error (4xx or 5xx).
• Apache can be configured to do one of four things:
▪ Send a simple hardcoded error message (default option).
▪ Send a customized message.
▪ Redirect to a internal local URL-path to handle the error.
▪ Redirect to an external URL to handle the error.
• Eg.
ErrorDocument 500 http://example.com/cgi-bin/server-error.cgi
ErrorDocument 404 /errors/bad_urls.php
ErrorDocument 401 /subscription_info.html
ErrorDocument 403 "Sorry, can't allow you access today“
ErrorDocument 403 /errors/forbidden.py?referrer=%{escape:%{HTTP_REFERER}}
ErrorDocument 404 default
24
Apache management
Log directives
• Log Files in Apache: Level
emerg
Description
Emergencies -
https://httpd.apache.org/docs/2.4/logs.html system is unusable.

alert Action must be


LogLevel (s,v,d) taken immediately.

crit Critical Conditions.


LogLevel [module:]level ...
▪ It adjusts the verbosity of the messages recorded in error Error conditions.

the error logs. Specifying a level with a module name warn Warning conditions.

will set the level for that module only. notice Normal but
significant condition.
▪ When a particular level is specified, messages from all
info Informational.
other levels of higher significance will be reported as
debug Debug-level
well. messages
▪ Eg.: trace1 – Trace messages
trace6
LogLevel warn (default) trace 7 – Trace messages,
trace8 dumping large
LogLevel info ssl:warn amounts of data

25
Apache management
Log directives
• ErrorLog (s,v)
ErrorLog file-path|syslog[:[facility][:tag]]
▪ Location where the server will log errors.
▪ If the file-path is not absolute then it is assumed to be relative to
the ServerRoot.
▪ Eg. ErrorLog "/var/log/apache/error.log"
• ErrorLogFormat (s,v)
ErrorLogFormat [connection|request] format
▪ Format specification for error log entries.
▪ Eg.
▪ ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [client %a]
%M“
▪ ErrorLogFormat request "[%{uc}t] [R:%L] UA:'%+{User-
Agent}i'“
▪ ErrorLogFormat connection "[%{uc}t] [C:%{c}L] local\
%a remote\ %A"
26
Apache management
Log directives
CustomLog (s,v)
CustomLog file format|nickname [env=[!]environment-variable|
expr=expression]
• Sets filename and format of log file for requests to the server.
• A log format is specified, and the logging can optionally be made
conditional on request characteristics using environment
variables.
LogFormat (s,v)
LogFormat format|nickname [nickname]
• Specifies the format of the access log file.
• Example:
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog "logs/access_log" common
27
Apache management
Log formats
Format Description
%% The percent sign
%a Client IP address of the request
%A Local IP address (server)
%B Size of response in bytes, excluding HTTP headers
%b Size of response in bytes, excluding HTTP headers. In CLF format.
%D The time taken to serve the request, in microseconds.
%f Filename
%h Remote hostname
%H The request protocol (eg. HTTP, HTTPS)
%m The request method.
%p The canonical port of the server serving the request.
%q The query string (prepended with a ? if a query string exists, otherwise an empty string)
%T The time taken to serve the request, in seconds
%U The URL path requested, not including any query string.
%v The canonical ServerName of the server serving the request.

28
Apache management
Directives
DirectoryIndex (s,v,d,h)
DirectoryIndex disabled | local-url [local-url] ...
▪ List of resources to look for, when the client requests an
index of the directory by specifying a / at the end of the
directory name. If none of the resources exist and
the Indexes option is set, the server will generate its own
listing of the directory.
▪ AllowOverride Indexes
▪ Example:
DirectoryIndex index.html index.htm index.php

Mercedes Rodríguez, septiembre 2021 29


Apache management
Directives
IndexIgnore (s,v,d,h)
IndexIgnore file [file] ...
▪ List of files to hide when listing a directory. File is a shell-
style wildcard expression or full filename.
▪ AllowOverride Indexes
▪ Example:
− IndexIgnore .??* *~ *# HEADER* README*

30
Apache management
Directives
• Options (s,v,d,h)
Options [+|-]option [[+|-]option] ...
▪ Configures what features are available in a particular
directory.
▪ AllowOverride Options
▪ Any options preceded by a + are added to the options currently in
force, and any options preceded by a - are removed from the options
currently in force.
▪ Example:
Options –Indexes +FollowSymLinks

31
Apache management
Directives
▪ Options example
<Directory /web/docs>
Options Indexes FollowSymLinks
</Directory>

<Directory /web/docs/spec>
Options +Includes -Indexes
</Directory>

The options FollowSymLinks and Includes are set for


the /web/docs/spec directory. Because listing of directory
/web/docs/spec is disabled, the server sends the message Error 403
Forbidden when the user specifies that directory in the URL.

32
Apache management
Directives
• Options parameters
▪ All: default
▪ Indexes: If a URL which maps to a directory is requested,
and there is no DirectoryIndex (e.g., index.html) in that
directory, then mod_autoindex will return a formatted
listing of the directory.
▪ Multiviews: It can choose the best representation of a
resource based on the browser-supplied preferences for
media type, languages, character set and encoding.
▪ FollowSymLinks: The server will follow symbolic links in
this directory.

33
Apache management
Directives for authorization (control access)
Require (d,h)
Require [not] entity-name [entity-name] ...
▪ Tests whether an authenticated user is authorized by an
authorization provider.
▪ AllowOverrride AuthConfig
• The authorization container directives <RequireAll>,
<RequireAny> and <RequireNone> may be combined with each
other and with the Require directive to express complex
authorization logic.
• HowTo “Authentication and Authorization”:
▪ https://httpd.apache.org/docs/2.4/en/howto/auth.html

34
Apache management
Require usage
Directive example Description
Require all granted Access is allowed unconditionally
Require all denied Access is denied unconditionally
Require method http-method Access is allowed only for the given HTTP methods
Require expr expression Access is allowed if expression evaluates to true
Require user userid ... Only the named users are allowed
Require valid-user All valid users are allowed (all users in passwords file)
Require group group-name ... Only users in the named groups are allowed
Require ip IP[/prefix] ... Clients from those IP ranges are allowed
Require host domain-name ... Clients from those domain names are allowed. It does a reverse DNS
lookup on the IP address to find the hostname, and then does a forward
lookup on the hostname to assure that it matches the original IP
address. Only if the forward and reverse DNS are consistent and the
hostname matches will access be allowed.
Require forward-dns hostname Reverse DNS is not used, it simply queries the DNS for the host name
and allows a client if its IP matches. It works only with host names and it
will work with clients which use DDNS.
Require local Possibilities: either IPv4 in 127/8, or IPv6= ::1, or both the client and
the server address of the connection are the same
35
Apache management
Require examples
<Directory "/www/docs">
<RequireAll>
Require group alpha beta
Require not group reject
</RequireAll>
</Directory>

<Directory "/www/docs">
AuthType Basic
AuthName "Restricted Resource"
AuthBasicProvider file
AuthUserFile "/web/users"
AuthGroupFile "/web/groups"
Require group admin
</Directory>

36
Apache management
Require containers example in complex authorization
In order to access /www/mydocs, the user must either be the ”superadmin”, or belong to both
the ”admins” group and the ”Administrators” LDAP group and either belong to the ”sales” group
or have the LDAP dept attribute ”sales”. Furthermore, the user must not belong to either
the ”temps” group or the LDAP group ”Temporary Employees”:
<Directory "/www/mydocs">
<RequireAll>
<RequireAny>
Require user superadmin
<RequireAll>
Require group admins
Require ldap-group "cn=Administrators,o=Airius"
<RequireAny>
Require group sales
Require ldap-attribute dept="sales"
</RequireAny>
</RequireAll>
</RequireAny>
<RequireNone>
Require group temps
Require ldap-group "cn=Temporary Employees,o=Airius"
</RequireNone>
</RequireAll>
</Directory>
37
Apache management
Directives for authentication
• Documentation: https://httpd.apache.org/docs/2.4/en/howto/auth.html
• Basic authentication (based in user or group of users):
▪ mod_auth_basic / AllowOverride Autconfig
▪ To create passwords’ file (without “–c”, it adds users to the file):
− htpasswd -c /usr/local/apache/passwd/passwords userName
▪ modify your .htaccess file or <Directory> block as follows:
AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
AuthUserFile "/path/to/file/passwords"
Require user userName

AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
AuthUserFile "/path/to/file/passwords"
AuthGroupFile "/path/to/file/groups“
Require group groupName

38
Apache management
.htaccess files
• http://httpd.apache.org/docs/2.4/howto/htaccess.ht
ml
• Use of .htaccess files:
▪ Perfomance issue. In general, use of .htaccess files should
be avoided when possible.
▪ Valid, for example, in cases where ISPs are hosting multiple
user sites on a single machine, and want their customers
to be able to alter their configuration.
▪ Can be disabled:
<Directory />
AllowOverride None
</Directory>

39
Apache management
.htaccess files
• AllowOverride (d)
AllowOverride All|None|directive-type [directive-type] ...
▪ Specifies directives that can be overrided in a .htaccess.
Directive-type Description Allowed directives
AuthConfig Authorization directives AuthGroupFile, AuthName, AuthType
, AuthUserFile, Require, etc…
FileInfo To control document types, ErrorDocument; mod_mime (Add*
document meta data, and Remove*) document meta data,
mod_rewrite directives,
mod_alias directives
Indexes To control directory indexing DirectoryIndex, IndexIgnore,
IndexOptions…
Limit To control host access Allow, Deny, Order
Options[=Option,...] To control specific directory features

40
Apache management
Directives. More containers
• <Location> and <LocationMatch regex>
• <Files filename> and <FilesMatch regex>
• <If>, <IfDefine>, <IfDirective>, <IfModule>,
<IfSection>

41
Apache management
Info and status modules: server monitoring
• mod_info: comprehensive overview of the server
configuration.
• mod_status: information on server activity and performance.
• Activating:
▪ # a2enmod info status #mod_info
▪ Adding conf in apache2.conf ➔ <Location /server-info>
SetHandler server-info
Require ip 127.0.0.1
Require ip your-ip
</Location>
#mod_status
<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1
Require ip your-ip
</Location>

42
Apache management
HTTPS, secure web server
• mod_ssl provides interface to the OpenSSL library, which provides Strong
Encryption using the SSL and TLS protocols.
• Introduction To SSL
• SSL/TLS Strong Encryption: How-To
• Basic settings:
LoadModule ssl_module modules/mod_ssl.so
Listen 443
<VirtualHost *:443>
ServerName www.example.com
SSLEngine on
SSLCertificateFile "/path/to/www.example.com.cert“
SLCertificateKeyFile "/path/to/www.example.com.key"
</VirtualHost>

• A good tutorial: How To Secure Apache with mod_md Let’s Encrypt on Ubuntu 20.04 LTS

43
Apache management
Credits
• Apache documentation: https://httpd.apache.org/docs/2.4//en/
• OpenSSL: https://www.openssl.org/
• How To Install the Apache Web Server on Ubuntu:
• https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-
server-on-ubuntu-22-04#step-5-setting-up-virtual-hosts-recommended
• Regular expressions online checking tool:
https://regex101.com/r/gO4eS8/5

44

You might also like