Complete Guide to Ubuntu Web Server | Apache + SSL + Optimization [Beginner-Friendly]

目次

1. Introduction

What is an Ubuntu Web Server?

A web server is a system that delivers websites over the internet. Popular web server software includes Apache, Nginx, and LiteSpeed, but the most widely used on Ubuntu is Apache.
Ubuntu is lightweight, highly stable, and open-source, making it a popular choice for both individuals and businesses. It is particularly suited for building a LAMP stack (Linux, Apache, MySQL/MariaDB, PHP), which is commonly used for running websites and web applications.

Who Is This Guide For?

This article is designed for beginners who are setting up a web server for the first time. It provides a step-by-step guide on how to install Apache on Ubuntu, configure virtual hosts, set up SSL certificates, optimize performance, and enhance security.

What You Will Learn

  • How to set up a web server on Ubuntu (Installing and configuring Apache)
  • Setting up virtual hosts to manage multiple websites
  • Installing free SSL certificates with Let’s Encrypt
  • Enhancing security and optimizing server performance
  • Troubleshooting common web server issues

2. Installing and Initial Setup of Ubuntu

System Requirements

To run Ubuntu as a web server, the following minimum system specifications are recommended:

ComponentMinimum RequirementsRecommended Requirements
OSUbuntu 22.04 LTSUbuntu 22.04 LTS
CPU1GHz or higher2GHz or higher
Memory512MB2GB or higher
Storage10GB or more20GB or more
NetworkInternet connectionHigh-speed connection recommended

Downloading and Installing Ubuntu

You can download Ubuntu from the official website: https://ubuntu.com/download/server. Once you obtain the ISO file, you can install it using VirtualBox or VMware for a virtual environment, or on a dedicated server or VPS.

Installation Steps:

  1. Create installation media
  • Use a USB drive (with tools like Rufus)
  • Mount the ISO file in a virtual machine
  1. Follow the installation wizard
  • Set language to English
  • Check network connectivity
  • Configure username and password
  • Install SSH server (optional, can be done later)
  1. Complete OS setup and restart
  2. Log in and begin initial configuration

Basic Initial Setup

After installation, perform the following initial setup steps:

  1. Update system packages
sudo apt update && sudo apt upgrade -y

→ This ensures that security patches and software updates are applied.

  1. Set the time zone
sudo timedatectl set-timezone America/New_York

→ Set the time zone to match your server location.

  1. Enable the firewall
sudo ufw enable

→ This protects the server from unauthorized access.

  1. Configure SSH (for remote management)
  • Check if SSH is enabled:
    sudo systemctl status ssh
  • If not enabled, start it:
    sudo systemctl enable --now ssh

Once these initial settings are applied, the Ubuntu server is ready to be configured as a web server.

3. Installing and Configuring Apache

What is Apache?

Apache (officially Apache HTTP Server) is an open-source web server software known for its stability, scalability, and security. Approximately 30% of web servers worldwide use Apache.

Key Features:

  • Free and open-source
  • Modular architecture for easy customization
  • Supports SSL/TLS for secure HTTPS connections
  • Virtual host support to manage multiple websites

Installing Apache

On Ubuntu, Apache can be installed easily using the apt package manager.

Install Apache

Run the following commands to install Apache:

sudo apt update
sudo apt install apache2 -y

Verify Installation

After installation, check the Apache version:

apache2 -v

Example output:

Server version: Apache/2.4.52 (Ubuntu)
Server built:   2023-07-01T12:34:56

If you see this message, Apache is installed successfully.

Starting, Stopping, and Restarting Apache

Apache is managed using the systemctl command.

Start Apache

sudo systemctl start apache2

Enable Apache to Start on Boot

sudo systemctl enable apache2

Check Apache Status

To confirm that Apache is running:

sudo systemctl status apache2

If Apache is running, you will see an “active (running)” status.

Restart or Stop Apache

If you need to restart Apache after making configuration changes:

sudo systemctl restart apache2

To temporarily stop Apache:

sudo systemctl stop apache2

4. Configuring Virtual Hosts (Managing Multiple Websites)

What is a Virtual Host?

A virtual host is a feature that allows a single Apache server to host multiple domains (or subdomains).
For example, a single server can host both example.com and test.com.

There are two types of virtual hosts:

  1. Name-based Virtual Host
  • Hosts multiple sites on the same IP address
  • The most common way to manage multiple websites
  1. IP-based Virtual Host
  • Each site is assigned a different IP address
  • Requires multiple network interfaces on the server

Typically, name-based virtual hosting is used.

Steps to Configure Virtual Hosts

1. Create Directories for Each Site

Each virtual host requires a dedicated directory to store its website files.

sudo mkdir -p /var/www/example.com/public_html
sudo mkdir -p /var/www/test.com/public_html

2. Change Ownership of the Directories

To ensure Apache can access the files, set the owner to www-data.

sudo chown -R www-data:www-data /var/www/example.com/public_html
sudo chown -R www-data:www-data /var/www/test.com/public_html

3. Create a Test HTML File

For verification, create an index.html file for each site.

echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/public_html/index.html
echo "<h1>Welcome to test.com</h1>" | sudo tee /var/www/test.com/public_html/index.html

4. Create Virtual Host Configuration Files

Virtual host configurations are stored in /etc/apache2/sites-available/.

Configuration for example.com

Create and edit a configuration file:

sudo nano /etc/apache2/sites-available/example.com.conf

Add the following configuration:

<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html

    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

Configuration for test.com

sudo nano /etc/apache2/sites-available/test.com.conf

Add the following content:

<VirtualHost *:80>
    ServerAdmin admin@test.com
    ServerName test.com
    ServerAlias www.test.com
    DocumentRoot /var/www/test.com/public_html

    <Directory /var/www/test.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/test.com_error.log
    CustomLog ${APACHE_LOG_DIR}/test.com_access.log combined
</VirtualHost>

5. Enable Virtual Hosts

Once the configuration files are created, enable them with a2ensite.

sudo a2ensite example.com.conf
sudo a2ensite test.com.conf

Test Apache Configuration

Check for syntax errors:

sudo apachectl configtest

If the output is:

Syntax OK

Restart Apache to apply changes:

sudo systemctl restart apache2

6. Testing Locally (Editing the hosts File)

To verify that the virtual hosts work correctly, edit your local hosts file.

sudo nano /etc/hosts

Add the following lines:

127.0.0.1 example.com
127.0.0.1 test.com

After saving, open a browser and enter:

http://example.com/

If you see **”Welcome to example.com”**, the setup is successful.

5. Enabling SSL/TLS (HTTPS)

What is SSL/TLS?

SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are encryption technologies that secure communication over the internet.

Benefits of SSL/TLS:

Encrypts communication (reduces risks of data theft and tampering)
Boosts SEO ranking (Google prioritizes HTTPS sites in search results)
Prevents browser warnings (HTTP sites may show “Not Secure”)
Secures online payments and login credentials

Using Let’s Encrypt for Free SSL

Let’s Encrypt is a certification authority that provides free SSL certificates. We use certbot to set it up easily.

Install Certbot

sudo apt update
sudo apt install certbot python3-certbot-apache -y

Automatically Configure SSL for Apache

sudo certbot --apache -d example.com -d www.example.com

Verify HTTPS is Working

After installation, check:

https://example.com/

If you see a **lock icon** in the browser, SSL is working.

6. Enhancing Web Server Security

Setting Up a Firewall (UFW)

Enable Firewall and Open Necessary Ports

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp   # SSH
sudo ufw allow 80/tcp   # HTTP
sudo ufw allow 443/tcp  # HTTPS
sudo ufw enable

Protecting SSH

Change SSH Port

sudo nano /etc/ssh/sshd_config

Change:

Port 2222  # Change 22 to a custom port

Restart SSH:

sudo systemctl restart ssh

7. Performance Optimization

Apache Tuning

By default, Apache is not always optimized for handling high traffic efficiently.
You can adjust the following settings to improve performance.

Optimizing MPM (Multi-Processing Module)

MPM (Multi-Processing Module) determines how Apache processes requests.

Check the current MPM configuration:

apachectl -M | grep mpm

Example output:

mpm_prefork_module (shared)

If you see mpm_prefork_module, consider switching to mpm_event for better performance.

Change to MPM Event:

sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2

Enabling KeepAlive

KeepAlive allows persistent connections, reducing the number of new requests.

Edit the Apache configuration file:

sudo nano /etc/apache2/apache2.conf

Add or modify the following settings:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

Restart Apache:

sudo systemctl restart apache2

Leveraging Caching

Using browser and server-side caching reduces redundant requests, improving response times.

Enable mod_expires for Browser Caching

sudo a2enmod expires
sudo systemctl restart apache2

Edit your virtual host configuration file:

sudo nano /etc/apache2/sites-available/example.com.conf

Add:

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

Restart Apache:

sudo systemctl restart apache2

Enable Gzip Compression

Enable compression to reduce file sizes and improve loading speed.

Enable mod_deflate

sudo a2enmod deflate
sudo systemctl restart apache2

Edit the virtual host configuration file:

sudo nano /etc/apache2/sites-available/example.com.conf

Add:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>

Restart Apache:

sudo systemctl restart apache2

Limiting Resources

To prevent excessive resource usage, limit the number of connections per IP.

Enable mod_ratelimit

sudo a2enmod ratelimit
sudo systemctl restart apache2

Edit the virtual host configuration file:

sudo nano /etc/apache2/sites-available/example.com.conf

Add:

<Location />
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 200
</Location>

Restart Apache:

sudo systemctl restart apache2

8. Troubleshooting

Apache Won’t Start or Stops Unexpectedly

Check Apache Status

sudo systemctl status apache2

If the output contains:

Active: failed

Then an error has occurred.

Check Error Logs

sudo journalctl -xe
sudo tail -f /var/log/apache2/error.log

Check Port Conflicts

sudo netstat -tulnp | grep ':80'

Or:

sudo lsof -i:80

SSL Certificate Issues

SSL Certificate Expired

sudo certbot renew --force-renewal

Apache SSL Configuration Error

Edit the Apache SSL configuration file:

sudo nano /etc/apache2/sites-available/example.com-le-ssl.conf

Verify:

SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

Restart Apache:

sudo systemctl restart apache2

Website Not Loading (403, 404, 500 Errors)

403 Forbidden

sudo chown -R www-data:www-data /var/www/example.com/public_html
sudo chmod -R 755 /var/www/example.com/public_html

404 Not Found

Check the virtual host configuration:

DocumentRoot /var/www/example.com/public_html

Enable mod_rewrite if necessary:

sudo a2enmod rewrite
sudo systemctl restart apache2

500 Internal Server Error

Check error logs:

sudo tail -f /var/log/apache2/error.log

Try renaming .htaccess:

mv /var/www/example.com/public_html/.htaccess /var/www/example.com/public_html/.htaccess.bak

9. Summary

What You Have Learned

Let’s review the key topics covered in this guide.

SectionKey Points
1. IntroductionOverview of Ubuntu Web Server and the purpose of this guide
2. Installing and Initial Setup of UbuntuSetting up Ubuntu, updating packages, and configuring the firewall
3. Installing and Configuring ApacheInstalling Apache, starting the service, and verifying functionality
4. Configuring Virtual HostsHosting multiple websites on a single Apache server
5. Enabling SSL/TLSUsing Let’s Encrypt for HTTPS setup
6. Enhancing Web Server SecurityFirewall setup, SSH security, and Apache hardening
7. Performance OptimizationUsing caching, compression, and tuning Apache settings
8. TroubleshootingFixing Apache errors, SSL issues, and common website errors

Next Steps

Now that your Ubuntu web server is up and running, consider learning about more advanced topics to enhance your server’s capabilities:

Deploying WordPress or PHP applications
Setting up a database server (MySQL / MariaDB)
Configuring Nginx as a reverse proxy for Apache
Implementing auto-scaling with cloud platforms (AWS, GCP, Azure)
Advanced logging and monitoring (Fail2Ban, Logwatch, Prometheus)

Frequently Asked Questions (FAQ)

Q1: Should I choose Nginx or Apache for my web server?

A1: If your website serves mainly static content, Nginx is recommended. If you need dynamic content processing (like PHP), Apache is a better choice. You can also use Nginx as a reverse proxy in front of Apache.

Q2: Can SSL certificates be renewed automatically?

A2: Yes, Certbot supports automatic renewal. You can check renewal status with:

sudo certbot renew --dry-run

For fully automatic renewal, it’s recommended to set up a cron job.

Q3: How can I further enhance my server security?

A3: Implement Fail2Ban to prevent brute-force attacks, hide Apache version details, disable unused modules, and enforce strong SSH security practices.

Q4: How can I improve Apache’s performance?

A4: Switch to MPM Event, enable caching (mod_cache), use gzip compression (mod_deflate), and optimize KeepAlive settings.

Q5: Why am I getting a “403 Forbidden” error?

A5: Ensure that the directory ownership is set to www-data and adjust file permissions:

sudo chown -R www-data:www-data /var/www/example.com/public_html
sudo chmod -R 755 /var/www/example.com/public_html

Final Thoughts

Setting up an Ubuntu web server involves multiple steps, from installation and configuration to optimization and troubleshooting. However, once you understand the process, you can build and manage a powerful web hosting environment.

🚀 Follow this guide to create a secure, fast, and reliable web server, and continue improving your skills as a server administrator! 🚀

年収訴求