SoFunction
Updated on 2025-04-12

Project Practice for Setting up Nginx Virtual Host in Ubuntu

Introduction

Nginx is a high-performance HTTP and reverse proxy server that is widely used to host multiple websites or applications. By configuring Virtual Hosts, multiple independent websites can be run on the same server. This article will guide you on how to set up a virtual host in Nginx.

Install Nginx

Make sure your server has Nginx installed. If not, you can install it using the following command:

sudo apt update
sudo apt install nginx

After the installation is complete, Nginx can be started and enabled via the following command:

sudo systemctl start nginx
sudo systemctl enable nginx

Create a virtual host

1. Create a website directory

Create a separate directory for each virtual host to store website files. For example,Create a directory:

sudo mkdir -p /var/www//html
sudo chmod -R 755 /var/www/

2. Create a default index file

Create a simple one in the website directorydocument:

echo "<html><body><h1>Welcome to !</h1></body></html>" | sudo tee /var/www//html/

3. Configure Nginx

Edit or create a new virtual host configuration file. Usually, these files are located in/etc/nginx/sites-available/In the directory. For example, createConfiguration file:

sudo nano /etc/nginx/sites-available/

Add the following to the configuration file:

server {
    listen 80;
    server_name  ;

    root /var/www//html;
    index  ;

    location / {
        try_files $uri $uri/ =404;
    }

    # Optional: Enable directory list    # location / {
    #     autoindex on;
    #     try_files $uri $uri/ =404;
    # }
}

Save and close the file.

4. Enable virtual hosting

Create a symbolic link to link the configuration file to/etc/nginx/sites-enabled/Directory to enable the virtual host:

sudo ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

Disable the default Nginx configuration (if not required):

sudo rm /etc/nginx/sites-enabled/default

Configuration file structure

The main configuration file of Nginx is usually located in/etc/nginx/, and the configuration file of the virtual host is usually located in/etc/nginx/sites-available/. You can link to/etc/nginx/sites-enabled/to enable these configuration files.

Sample configuration file

server {
    listen 80;
    server_name  ;

    root /var/www//html;
    index  ;

    location / {
        try_files $uri $uri/ =404;
    }

    # Access logs and error logs    access_log /var/log/nginx/ combined;
    error_log /var/log/nginx/ warn;
}

Set up access logs and error logs

For better monitoring and debugging, it is recommended to set up independent access logs and error logs for each virtual host. You canserverAdd the following instructions to the block:

access_log /var/log/nginx/ combined;
error_log /var/log/nginx/ warn;

This will beCreate independent log files to record access requests and error messages separately.

Handling 403 Forbidden Error

If you encounter403 ForbiddenError, which may be due to the following reasons:

No settingsindexdocument

Make sure there is a default index file in the website directory (such asor)。

existserverAdd to the blockindexDirective, specifying the index file to be used.

Directory list disabled

If you want users to be able to access the directory contents but do not want to provide the default index file, you canlocationAdd to the blockautoindex on;

File and directory permission issues

Ensure that Nginx is running (usuallywww-data) Have permission to read the website directory and its files.

Use the following command to set the correct permissions:

sudo chown -R www-data:www-data /var/www/
sudo chmod -R 755 /var/www/

SELinux or AppArmor settings

If the system has SELinux or AppArmor enabled, these security modules may restrict Nginx from accessing files. You can view the status through the following command:

sudo aa-status
sudo sestatus

Test and restart Nginx

After making any changes to the configuration file, remember to test whether the Nginx configuration is correct and reload or restart the Nginx service:

sudo nginx -t
sudo systemctl reload nginx
# orsudo service nginx reload

Nginx Directory Important Files and Directories

Main Directory and Files

  • /etc/nginx/: The main configuration file of Nginx.
  • /etc/nginx/sites-available/: The directory where the virtual host configuration file is stored.
  • /etc/nginx/sites-enabled/: The directory where the enabled virtual host configuration files are stored.
  • /var/log/nginx/: The directory where Nginx log files are stored.
  • /var/www/: The directory where the website files are stored.

Files and directories in pictures

According to the pictures provided, the following are the important files and directories:

  • : The directory where additional configuration files are stored.
  • modules-available: The directory where available modules are stored.
  • modules-enabled: The directory where the enabled module is stored.
  • sites-available: The directory where the virtual host configuration file is stored.
  • sites-enabled: The directory where the virtual host configuration file is enabled.

Detailed explanation of the server_name command

server_nameDirectives are used to specify which domain names Nginx should respond to. It is a very important directive, especially when configuring a virtual host. The following isserver_nameDetailed description and common usages of  :

grammar

server_name  [ ...];

Common usage

Single domain name
If you only have one domain name, you can directlyserver_nameWrite the domain name later:

server {
    listen 80;
    server_name ;

    #Other configurations...}

Multiple domain names
If you have multiple domain names pointing to the same website, you canserver_nameAll domain names are listed later, separated by spaces:

server {
    listen 80;
    server_name  ;

    #Other configurations...}

Domain with wildcard characters
If you have a set of subdomains, you can use wildcards to match those subdomains. For example,*.Can match allSubdomain name:

server {
    listen 80;
    server_name *.;

    #Other configurations...}

IP address
You can also use the IP address asserver_name, which is particularly useful in testing environments:

server {
    listen 80;
    server_name 192.168.1.100;

    #Other configurations...}

Default server
If you don't specifyserver_nameOr hope Nginx responds to all other things that are not matchedserver_nameFor requests, you can use underscore_Asserver_name, or omitserver_nameAnd usedefault_serverParameters:

server {
    listen 80 default_server;
    # or    server_name _;

    #Other configurations...}

Special circumstances

Exact match
You can use=To perform exact matches, it will only take effect when the requested domain name matches exactly:

server {
    listen 80;
    server_name = ;

    #Other configurations...}

Regular expressions
You can use regular expressions to match complex domain patterns. Regular expressions need to be~Starting:

server {
    listen 80;
    server_name ~^(www\.)?(?&lt;domain&gt;.+)$;

    #Other configurations...}

In this example,andThey will match, and you can pass$domainVariable acquisition and removalwww.The domain name afterward.

Things to note

  • DNS resolution: Make sure your domain name has been correctly resolved to the server's IP address. You can passpingornslookupThe command checks whether the domain name resolution is correct.
  • SSL/TLS configuration: If you use HTTPS, you also need to configure the SSL certificate and key and thenlistenChange the command tolisten 443 ssl;
  • Firewall settings: Ensure that the server's firewall allows traffic to HTTP (80) and HTTPS (443) ports.

Example: Complete virtual host configuration

server {
    listen 80;
    server_name  ;

    root /var/www//html;
    index  ;

    location / {
        try_files $uri $uri/ =404;
    }

    # Access logs and error logs    access_log /var/log/nginx/ combined;
    error_log /var/log/nginx/ warn;
}

Reference resources

  • Nginx official documentation
  • Ubuntu Nginx official documentation
  • Nginx virtual host configuration tutorial

Summarize

Through the above steps, you should be able to successfully set up a virtual host in Nginx.server_nameDirectives are a key part of configuring virtual hosts to ensure that you have correctly set up domain names, wildcards, or other matching rules. If you have any problems, check Nginx's error log for more clues. I hope this note can help you configure Nginx virtual host smoothly!

This is the article about the project practice of Nginx virtual host settings in Ubuntu. For more related content on Nginx virtual host settings, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!