How to Create Virtual Host in Nginx: Simple Guide
To create a virtual host in
nginx, define a server block inside the configuration files, specifying the server_name and root directory. Then reload nginx to apply the changes.Syntax
The basic syntax for creating a virtual host in nginx uses a server block. Inside it, you specify the listen port, server_name for the domain, and root for the website files.
- listen: Port number to listen on (usually 80 for HTTP).
- server_name: Domain or IP address for this virtual host.
- root: Path to the website files served.
- index: Default file to serve (like index.html).
nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}Example
This example shows a complete virtual host configuration for the domain example.com. It listens on port 80 and serves files from /var/www/example.com/html. The location block handles requests and returns a 404 error if the file is not found.
nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}Output
nginx: configuration file /etc/nginx/nginx.conf test is successful
Reloading nginx: nginx.
Common Pitfalls
Common mistakes when creating virtual hosts in nginx include:
- Forgetting to reload or restart
nginxafter changes. - Not setting correct
server_name, causing requests to go to the default server. - Incorrect
rootpath or missing website files. - Syntax errors in the config file causing
nginxto fail.
Always test your configuration with nginx -t before reloading.
bash
## Wrong: Missing reload # sudo nginx -t # sudo systemctl reload nginx ## Right: sudo nginx -t sudo systemctl reload nginx
Output
nginx: configuration file /etc/nginx/nginx.conf test is successful
Reloading nginx: nginx.
Quick Reference
| Directive | Purpose |
|---|---|
| listen | Port number to listen on (e.g., 80 for HTTP) |
| server_name | Domain names this virtual host responds to |
| root | Directory path for website files |
| index | Default file to serve (e.g., index.html) |
| location | Block to define request handling rules |
Key Takeaways
Define a
server block with listen, server_name, and root to create a virtual host.Always test your configuration with
nginx -t before reloading the server.Reload
nginx after changes to apply the new virtual host settings.Ensure the
server_name matches the domain you want to serve.Check that the
root directory contains your website files.