How to Configure ServerName in Apache?
Configuring the ServerName directive in Apache is a
foundational step in web server administration, ensuring that your
server correctly identifies itself and routes web traffic to the
appropriate website. This guide provides a straightforward overview of
how ServerName works, where to locate it in your
configuration files, and the exact steps required to set it up for both
global server identification and individual Virtual Hosts.
Understanding the ServerName Directive
The ServerName directive tells the Apache HTTP Server
its own hostname and port. It is primarily used for two critical
functions:
- Generating Self-Referencing URLs: When Apache
redirects a user, it uses the
ServerNameto construct the correct URL. Without it, the server might attempt to use the client’s requested hostname or the server’s internal IP address, often leading to broken links. - Virtual Host Matching: In a shared hosting
environment where multiple websites run on a single IP address, Apache
uses the
ServerName(andServerAlias) within a<VirtualHost>block to determine which website’s files should be served to the visitor.
Step-by-Step Configuration
To configure ServerName, you will need administrative
access (sudo privileges) to your server’s terminal.
1. Locate Your Configuration File
Depending on your operating system, the main Apache configuration file or the Virtual Host files are located in different directories:
- Ubuntu / Debian:
/etc/apache2/apache2.conf(global) or/etc/apache2/sites-available/your-site.conf(virtual hosts). - CentOS / RHEL / Fedora:
/etc/httpd/conf/httpd.conf.
2. Configure Global ServerName
If you do not set a global ServerName, Apache will
generate a harmless but annoying warning when restarting: “Could not
reliably determine the server’s fully qualified domain name”.
To fix this, open your main configuration file and add or modify the directive at the global level:
ServerName your-server-ip-or-domain.com3. Configure ServerName for Virtual Hosts
To map a specific domain name to a specific website on your server,
place the ServerName directive inside the corresponding
<VirtualHost> block. You can also use
ServerAlias to match variations like the “www”
subdomain.
<VirtualHost *:80>
ServerAdmin webmaster@example.com
DocumentRoot /var/www/example.com/public_html
ServerName example.com
ServerAlias www.example.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>4. Test and Restart Apache
Before applying the changes, always check your Apache configuration syntax for errors to avoid crashing your web server.
Run the syntax test command:
- Ubuntu/Debian:
sudo apache2ctl configtest - CentOS/RHEL:
sudo httpd -t
If the output says Syntax OK, safely restart the Apache service to apply your new settings:
- Ubuntu/Debian:
sudo systemctl restart apache2 - CentOS/RHEL:
sudo systemctl restart httpd