Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Set Up Apache Virtual Hosts on Ubuntu

A practical Ubuntu guide to creating Apache name-based virtual hosts, enabling and checking site files, testing before DNS changes, fixing default-page problems, and extending the setup to HTTPS.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To host multiple websites on one Ubuntu server, create one Apache virtual-host definition per hostname in /etc/apache2/sites-available, enable each definition with a2ensite, verify the parsed order with apachectl -S, reload Apache, and point DNS (or a temporary hosts-file entry) at the server. Apache then selects the matching site from the hostname in each request.

What an Apache virtual host does

An Apache virtual host is a set of instructions that tells one Apache service which files and settings to use for a particular hostname. With name-based virtual hosting, several domains can share one IP address. The browser sends a hostname, Apache compares it with each virtual host’s ServerName and ServerAlias, and Apache serves the matching DocumentRoot.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Name-based hosting is normally the simplest arrangement because DNS sends several names to the same address and Apache distinguishes them after the request arrives. You do not need a separate public IP for every website.

Approach How Apache chooses a site When it makes sense
Name-based hosting Matches the request hostname against ServerName and ServerAlias on a shared address and port. Most multi-site Ubuntu servers; several domains share one IP.
IP-based hosting Uses different local IP addresses, with hosts grouped by address and port. Only when separate addresses are available and required by the design.

This guide uses a name-based HTTP configuration on port 80, then explains what changes for HTTPS on port 443.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

What you need before creating a site

  • An Ubuntu server with administrative access through sudo.
  • Apache2 installed, or permission to install it.
  • A hostname for each site, such as example.com and www.example.com.
  • A separate directory for each site’s files.
  • For public visitors, DNS A and/or AAAA records that resolve the hostname to the server’s address.

Apache configuration and DNS are separate systems. Enabling a site file does not create DNS records, and changing DNS does not create an Apache virtual host. A temporary entry in a client’s hosts file changes name resolution only on that one machine; it is useful for testing, but it does not make the site publicly reachable.

Set up the first HTTP virtual host

1. Install Apache2 and confirm the service

If Apache is not installed, install the Ubuntu package and start the service:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo apt update
sudo apt install apache2
sudo systemctl status apache2

The status command should show that the service is running. If it is not running, start it with:

sudo systemctl start apache2

Do not create several site files until the base service is working. A running default site gives you a known starting point for later hostname tests.

2. Create a separate document directory

Keep each website’s files in its own directory. For this example, create /var/www/example.com and a small index file:

sudo mkdir -p /var/www/example.com
sudo sh -c 'printf "%sn" "<!doctype html>" "<html><head><meta charset="utf-8"><title>example.com</title></head><body><h1>example.com is working</h1></body></html>" > /var/www/example.com/index.html'

The important part is that the directory in the virtual-host file exactly matches the directory containing the site’s files. A typo in DocumentRoot can make a correctly matched hostname appear broken.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Create the site definition in sites-available

Ubuntu keeps available site definitions in /etc/apache2/sites-available. Create a file named after the hostname:

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

Enter this configuration:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>

ServerName is the primary hostname Apache should match. ServerAlias adds other names, such as the www form. DocumentRoot identifies the directory whose files Apache serves. The log directives give this site its own error and access logs under Apache’s configured log directory.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Save the file and exit the editor. The filename can differ, but using example.com.conf makes the site easy to identify when enabling or disabling it.

4. Enable the virtual host

Creating a file in sites-available does not activate it. Enable it with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo a2ensite example.com.conf

a2ensite enables the named definition so Apache includes it in its active configuration. If you later need to remove this site from Apache’s active set without deleting the file, use:

sudo a2dissite example.com.conf

5. Inspect Apache’s parsed virtual-host map

Before reloading, ask Apache how it has parsed the address, port, names, and file order:

sudo apachectl -S

This output is especially useful when several files are enabled. It shows which virtual host is first for each address and port, and therefore which host will be the fallback. Look for the expected ServerName, every required alias, and the intended document-root file.

6. Reload Apache

Apply the enabled configuration without a full service stop:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo systemctl reload apache2

A reload is normally preferable for a configuration change because the service remains available while workers adopt the new settings. If a reload does not apply a change or the service is in a failed state, perform a full restart:

sudo systemctl restart apache2
Operation Use it when Effect
systemctl reload apache2 A valid configuration has changed. Apache rereads its configuration with less disruption.
systemctl restart apache2 A reload is insufficient or the service must be fully restarted. Stops and starts the service again, so expect more disruption.

Add additional websites on the same server

Repeat the same pattern for every hostname: create a distinct document directory, create a distinct file in sites-available, set a unique ServerName, add any aliases, enable the file, inspect the map, and reload Apache. For a second site, the configuration might look like this:

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
<VirtualHost *:80>
    ServerName second.example
    ServerAlias www.second.example
    DocumentRoot /var/www/second.example

    ErrorLog ${APACHE_LOG_DIR}/second.example-error.log
    CustomLog ${APACHE_LOG_DIR}/second.example-access.log combined
</VirtualHost>

Save it as /etc/apache2/sites-available/second.example.conf, then run:

sudo a2ensite second.example.conf
sudo apachectl -S
sudo systemctl reload apache2

The two definitions can share *:80 because Apache uses the hostname to distinguish them. They should not point to the same document directory unless serving identical content is intentional.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand fallback order and the Apache default page

Apache first groups virtual hosts by the most specific address and port. Within that group it compares the request hostname with ServerName and ServerAlias. If no name matches, Apache sends the request to the first listed virtual host for that address and port.

This fallback explains a common symptom: you enable a new site successfully but still see Ubuntu’s default page. The request may be using a hostname that is not listed, may be reaching the wrong address, or may be falling through to the first host because of a name typo. The default file is commonly named 000-default.conf, and its position can make it the fallback.

For a controlled test in which you do not want the default site involved, disable it:

sudo a2dissite 000-default.conf
sudo apachectl -S
sudo systemctl reload apache2

In production, keep a deliberate fallback site when appropriate. A fallback can provide a clear response for unknown hostnames instead of exposing whichever site’s content happens to be listed first.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the site before changing public DNS

Use a temporary hosts-file entry

You can test the hostname from one client before DNS is changed. Add the server’s IP address and hostname to that client’s hosts file. On Linux, the file is /etc/hosts; on Windows, it is typically C:WindowsSystem32driversetchosts; on macOS, it is also /etc/hosts.

Add a line using the server address, for example:

203.0.113.10 example.com www.example.com

Replace the example address with the actual server address. Then open the hostname in a browser from that same client. Apache will receive the intended Host header while only that machine uses the override. Remove the line after testing or when public DNS is active.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

A hosts-file entry is not a substitute for DNS. Other computers, mobile devices, and public visitors will continue using their normal DNS answers.

Point public DNS after the local test

Create the required A record for an IPv4 address and/or AAAA record for an IPv6 address at your DNS provider. Each hostname used in ServerName or ServerAlias must resolve to the server that runs this Apache configuration. Apache’s own documentation makes the dependency explicit: names must exist in DNS and resolve to the server’s IP address or other users cannot see the site.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After DNS changes, verify that the hostname resolves to the expected address from an external network, then request the hostname rather than the raw IP. Requesting only the IP may select the fallback virtual host because it does not provide the name you configured.

How Apache chooses among matching hosts

  1. Apache considers the address and port received by the connection, such as *:80.
  2. It narrows the candidates to virtual hosts configured for that address and port.
  3. It compares the request hostname with each ServerName and ServerAlias.
  4. If one matches, Apache serves that virtual host’s DocumentRoot and applies its directives.
  5. If none matches, Apache uses the first listed virtual host for that address and port.

The order shown by apachectl -S is therefore operational information, not cosmetic output. A duplicate name, misspelled alias, or unexpectedly early default file can change which content visitors receive.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot the most common failures

The Ubuntu default page still appears

  • Confirm that the browser is using the configured hostname, not only the server IP.
  • Check that the hostname exactly matches ServerName or one of the ServerAlias values.
  • Run sudo apachectl -S and see whether the intended host is listed and enabled.
  • Check whether DNS points to a different server.
  • If this is a controlled test, disable 000-default.conf and reload Apache.
  • Verify that the intended DocumentRoot contains the expected index file.

Do not assume that a successful a2ensite means every request will match the new host. Enabling changes the configuration set; hostname matching still depends on the incoming request and DNS path.

The hostname works locally but not publicly

A hosts-file override can make a site appear fixed on the test computer while public DNS still points elsewhere. Remove or inspect the override, query the public A or AAAA record, and ensure it resolves to the Apache server. Remember that hosts-file edits are local and invisible to everyone else.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An alias such as www fails

Add the alternate name to ServerAlias and ensure that the alias itself has a DNS record resolving to the server. Reload Apache after editing the file, then confirm the alias appears in apachectl -S output or in the active configuration map.

The site serves the wrong files

Compare the configured DocumentRoot character for character with the directory where you placed the index file. If another virtual host uses the same address and the request hostname does not match, Apache will serve that host’s root instead. Check the request name, aliases, and fallback order before moving files.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Apache does not adopt the change

Run sudo apachectl -S again to see what Apache currently parses. Confirm that you edited the file in /etc/apache2/sites-available, enabled the correct filename, and reloaded the service. Use a restart only when a reload is insufficient; a restart does not correct a misspelled hostname or a DNS record pointing to another machine.

Extend the configuration for HTTPS

HTTPS is a second virtual-host context, not merely a change to the port-80 block. Create or enable a virtual host on port 443 and configure the certificate and private-key paths supplied by your certificate issuer. The HTTPS definition needs the same hostname mapping concepts, but it listens on *:443 and includes TLS settings.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<VirtualHost *:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

    SSLEngine on
    SSLCertificateFile /path/supplied-by-your-certificate-issuer/certificate.pem
    SSLCertificateKeyFile /path-supplied-by-your-certificate-issuer/private-key.pem
</VirtualHost>

The exact certificate paths depend on the certificate authority and issuance method; do not copy the placeholder paths above into production. Enable the appropriate SSL support and the port-443 site according to the certificate provider’s instructions, then inspect the result with apachectl -S and reload Apache.

For HTTPS, Apache can use TLS Server Name Indication (SNI). The client sends the requested hostname during the TLS handshake, allowing Apache to select the correct SSL virtual host when several HTTPS sites share an address. A certificate must cover every hostname you expect clients to use, including aliases such as www.

Certificate issuance and renewal are separate operational tasks. They depend on the certificate authority and are not completed merely by creating an Apache virtual-host block.

A repeatable multi-site workflow

  1. Choose the hostname and its aliases.
  2. Create a unique directory such as /var/www/example.com and place an index file there.
  3. Create /etc/apache2/sites-available/example.com.conf with ServerName, optional ServerAlias, and the matching DocumentRoot.
  4. Enable it with sudo a2ensite example.com.conf.
  5. Run sudo apachectl -S and inspect names, ports, file paths, and fallback order.
  6. Reload Apache with sudo systemctl reload apache2.
  7. Test with a temporary hosts-file entry before changing public DNS.
  8. Point the public A and/or AAAA records at the server.
  9. For HTTPS, add the port-443 host, certificate paths, and SNI-compatible name coverage.

Keeping this sequence consistent makes failures easier to isolate: filesystem problems stay separate from Apache matching problems, and Apache problems stay separate from DNS problems.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational checklist

  • Every public hostname resolves to the server’s address.
  • Every hostname used by visitors appears in ServerName or ServerAlias.
  • Each site has the intended, distinct DocumentRoot.
  • The site file is in /etc/apache2/sites-available and enabled with a2ensite.
  • apachectl -S shows the expected address, port, names, and first-listed fallback.
  • Apache has been reloaded after the final edit.
  • Local hosts-file testing has been removed or documented so it does not hide a DNS error.
  • HTTPS has a separate port-443 definition and certificate configuration for every required name.

Final takeaway

Multiple websites on Ubuntu Apache require three pieces to agree: the files in each document directory, the virtual-host definitions Apache has enabled, and DNS that sends each hostname to the correct server. Build one isolated definition per site, verify Apache’s parsed order with apachectl -S, test locally with a hosts-file override, and only then publish DNS and add the HTTPS host.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.