Table of Contents
1. Understand the Basic Structure of a Server Block
2. Create the Directory Structure for Your Site
3. Enable the Server Block and Test Configuration
4. Handle Common Issues and Gotchas
Home Operation and Maintenance Nginx How to set up an Nginx server block (virtual host)?

How to set up an Nginx server block (virtual host)?

Jul 19, 2025 am 02:00 AM
nginx virtual host

To set up an Nginx server block, first understand its structure using the server directive with settings like listen, server_name, and location; next, create a directory structure for your site such as /var/www/example.com/html and set proper permissions; then enable the server block by creating a symbolic link from sites-available to sites-enabled and test configuration with nginx -t before reloading Nginx; finally, troubleshoot issues like port conflicts, incorrect root paths, multiple matching server blocks, missing index files, browser caching, or local DNS setup. Following these steps ensures smooth deployment of multiple websites on one server.

How to set up an Nginx server block (virtual host)?

Setting up an Nginx server block (also known as a virtual host in Apache terms) is a common task when hosting multiple websites on a single server. It allows you to serve different content based on the domain name requested by the client. The process is straightforward once you understand how Nginx interprets configuration files.


1. Understand the Basic Structure of a Server Block

A server block in Nginx is defined using the server directive inside the main config file or in separate files under /etc/nginx/sites-available/. You can think of it like a container that tells Nginx how to respond to requests for a specific domain.

Here’s a basic skeleton:

server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        root /var/www/example.com/html;
        index index.html;
        try_files $uri $uri/ =404;
    }
}
  • listen defines which port this server block listens on.
  • server_name is the domain(s) this block responds to.
  • location / sets how the root request should be handled — where to find files, what to do if they're missing, etc.

You can add more directives depending on your needs, like handling PHP files, setting up redirects, or configuring SSL later.


2. Create the Directory Structure for Your Site

Before setting up the server block, make sure you have a directory for your site's files. A typical setup looks like:

/var/www/example.com/
└── html/
    └── index.html

You can create this with:

sudo mkdir -p /var/www/example.com/html

Then place your HTML files inside the html folder. This keeps things organized, especially if you manage multiple domains.

Also, ensure the permissions are correct so Nginx can read the files:

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

3. Enable the Server Block and Test Configuration

Once the config file is ready, here’s what to do next:

  • Save the server block in /etc/nginx/sites-available/example.com.
  • Create a symbolic link to enable it:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

This makes Nginx aware of the new site.

After that, test your configuration for syntax errors:

sudo nginx -t

If everything looks good, reload Nginx to apply the changes:

sudo systemctl reload nginx

Now, if your DNS points example.com to your server IP, you should see your website live.


4. Handle Common Issues and Gotchas

Even if you follow all steps, sometimes things don’t work right away. Here are some common issues and how to fix them:

  • Port conflicts: Make sure no other service is using port 80 (e.g., Apache).
  • Wrong root path: Double-check the root directive matches where your files are.
  • Multiple server blocks matching the same domain: Nginx uses the first match alphabetically unless you specify default_server in listen.
  • Missing index file: If index.html doesn’t exist, you’ll get a 403 error.
  • Caching issues in browser: Try clearing cache or testing from a private window.

Also, keep in mind that if you’re testing locally, you may need to edit your local machine’s hosts file to point example.com to your server’s IP address.


That’s basically it. Once you’ve got one working, adding more sites becomes a matter of copying the structure and tweaking the domain and paths. Not too bad once you know where everything fits.

The above is the detailed content of How to set up an Nginx server block (virtual host)?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization model How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization model Jul 23, 2025 pm 07:21 PM

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services Jul 25, 2025 pm 08:24 PM

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

How to use Kubernetes to keep PHP environment consistent Production and local container configuration standards How to use Kubernetes to keep PHP environment consistent Production and local container configuration standards Jul 25, 2025 pm 06:21 PM

To solve the problem of inconsistency between PHP environment and production, the core is to use Kubernetes' containerization and orchestration capabilities to achieve environmental consistency. The specific steps are as follows: 1. Build a unified Docker image, including all PHP versions, extensions, dependencies and web server configurations to ensure that the same image is used in development and production; 2. Use Kubernetes' ConfigMap and Secret to manage non-sensitive and sensitive configurations, and achieve flexible switching of different environment configurations through volume mounts or environment variable injection; 3. Ensure application behavior consistency through unified Kubernetes deployment definition files (such as Deployment and Service) and include in version control; 4.

How to use PHP to develop e-commerce backend monetization PHP e-commerce system architecture and profit strategy How to use PHP to develop e-commerce backend monetization PHP e-commerce system architecture and profit strategy Jul 25, 2025 pm 06:33 PM

1. The mainstream frameworks of PHP e-commerce backend include Laravel (fast development, strong ecology), Symfony (enterprise-level, stable structure), Yii (excellent performance, suitable for standardized modules); 2. The technology stack needs to be equipped with MySQL Redis cache, RabbitMQ/Kafka message queue, Nginx PHP-FPM, and front-end separation is considered; 3. High concurrency architecture should be layered and modular, database read and write separation/distributed database, accelerated with cache and CDN, asynchronous processing of tasks, sharing of load balancing and Session, gradually microservice, and establish a monitoring and alarm system; 4. Multiple monetization paths include product price difference or platform commission, site advertising, SaaS subscription, customized development and plug-in market, API connection

How to test my Nginx configuration for syntax errors before reloading? How to test my Nginx configuration for syntax errors before reloading? Jul 13, 2025 am 01:06 AM

After modifying the Nginx configuration, you should first test the syntax and then reload the service. 1. Use nginx-t to check the configuration file syntax. If the prompt "syntaxisok" and "testissuccessful" are prompted, it means that it is correct; if there is an error, the specific problem line will be displayed. 2. If the configuration file permissions are high, you need to use sudonginx-t to execute. 3. Confirm that the test is actually loaded. You can specify the path through nginx-t-c/path/to/your/nginx.conf, or view the configuration file used by the main process through ps-ef|grepnginx. 4. After the test is passed, execute sudonginx-sreload overload service to make the new configuration take effect

How to configure MongoDB support for PHP environment Settings for PHP connection to Mongo database How to configure MongoDB support for PHP environment Settings for PHP connection to Mongo database Jul 23, 2025 pm 06:54 PM

To configure the PHP environment to support MongoDB, the core step is to install and enable the PHP driver of MongoDB to enable the PHP application to communicate with the MongoDB database. 1. Install MongoDBPHP driver, it is recommended to use PECL to install. If there is no PECL, you need to first install the PHP development package and related compilation tools; 2. Edit the php.ini file and add extension=mongodb.so (or .dll) to enable the extension; 3. Restart the web server or PHP-FPM service to make the configuration take effect; 4. Verify whether the extension is loaded successfully through phpinfo() or php-m. Frequently asked questions include missing PECL commands, compilation errors, php.ini

How to configure an Nginx server block for SSL/TLS on port 443? How to configure an Nginx server block for SSL/TLS on port 443? Jul 14, 2025 am 01:27 AM

To configure Nginx's SSL/TLS service, you need to prepare the certificate and private key and set the relevant parameters in the serverblock. 1. Prepare the certificate file: Obtain the certificate in .crt or .pem format and the corresponding .key private key. You can use Let'sEncrypt or commercial organization to issue it, and merge the intermediate certificate into the bundle file; 2. Configure the serverblock: define listen443ssl, ssl_certificate path as /etc/ssl/example.com.crt, and ssl_certificate_key path as /etc/ssl/example.com.k in the site configuration file.

PHP realizes image upload and processing monetization PHP image management and optimization technology PHP realizes image upload and processing monetization PHP image management and optimization technology Jul 25, 2025 pm 06:06 PM

Effectively managing massive images requires CDN or cloud storage to improve performance and scalability; 2. Optimize file structure through reasonable naming rules and directory storage; 3. Use PHP to automatically compress and convert it into efficient formats such as WebP to reduce volume; 4. Combine front-end responsive images and lazy loading technology to improve loading speed; 5. Realize signature URL anti-theft chain and upload security verification to prevent malicious files, thereby building a safe and efficient picture system to support commercial monetization.

See all articles