NGINX Virtual Host Configuration - Complete Guide
Table of Contents
- Introduction to NGINX
- Understanding Virtual Hosts
- NGINX Installation and Basic Setup
- Virtual Host Configuration Fundamentals
- Server Blocks Configuration
- Advanced Virtual Host Configurations
- SSL/TLS Configuration
- Troubleshooting and Common Issues
- Best Practices and Security
- Performance Optimization
Introduction to NGINX
NGINX (pronounced "engine-x") is a powerful, open-source web server that has gained popularity for its high performance and efficiency. Originally developed by Igor Sysoev in 2004, it uses an event-driven, asynchronous architecture to handle a high volume of connections simultaneously with minimal resource consumption. NGINX can also function as a reverse proxy, load balancer, mail proxy, and HTTP cache.
Key Features of NGINX
- Event-Driven Architecture: Uses an asynchronous approach to handle requests efficiently.
- High Concurrency: Manages thousands of connections with a minimal memory footprint.
- Reverse Proxy and Load Balancer: Distributes incoming requests to multiple servers.
- Static Content Serving: Efficiently serves static files like HTML, CSS, and images.
- SSL/TLS Support: Provides secure communications.
- WebSocket Support: Facilitates real-time web applications.
- FastCGI and uWSGI Support: Interfaces with applications written in languages like PHP and Python.
Understanding Virtual Hosts
Virtual hosting is a method that allows multiple websites to be hosted on a single physical server. Each site can have its own configuration, domain name, and resources.
Types of Virtual Hosts
- Name-Based Virtual Hosting
- Explanation: Multiple domains share a single IP address. The server distinguishes between domains using the
Host
header in the HTTP request. - Use Case: Common in most hosting environments.
- Explanation: Multiple domains share a single IP address. The server distinguishes between domains using the
- IP-Based Virtual Hosting
- Explanation: Each domain is associated with a unique IP address. The server identifies the site to serve based on the IP address.
- Use Case: Useful in specific scenarios, such as certain SSL/TLS configurations or when using legacy systems.
NGINX Installation and Basic Setup
Before configuring virtual hosts, you need to install and set up NGINX on your system.
Installation on Ubuntu/Debian
Update Package List:
sudo apt update
- Explanation: Ensures that your system has the latest package information.
Install NGINX:
sudo apt install nginx
- Explanation: Downloads and installs the NGINX package along with its dependencies.
Verify Installation:
nginx -v
- Explanation: Confirms that NGINX is installed and shows the installed version.
Start and Enable NGINX:
sudo systemctl start nginx sudo systemctl enable nginx
- Explanation: Starts NGINX and enables it to run automatically at system startup.
Check NGINX Status:
sudo systemctl status nginx
- Explanation: Displays the current status of the NGINX service.
Installation on CentOS/RHEL
Install EPEL Repository:
sudo yum install epel-release
- Explanation: Adds the Extra Packages for Enterprise Linux (EPEL) repository, which contains additional software packages, including NGINX.
Install NGINX:
sudo yum install nginx
- Explanation: Installs NGINX using the
yum
package manager.
- Explanation: Installs NGINX using the
Start and Enable NGINX:
sudo systemctl start nginx sudo systemctl enable nginx
- Explanation: Initiates NGINX and ensures it starts on boot.
NGINX Directory Structure
Understanding the NGINX directory structure is crucial for efficient configuration management.
/etc/nginx/
├── nginx.conf # Main configuration file
├── conf.d/ # Directory for general configurations
├── sites-available/ # Stores individual site configuration files
├── sites-enabled/ # Symlinks to active site configurations
├── modules-enabled/ # Enabled NGINX modules
└── modules-available/ # Available NGINX modules
- Explanation: The separation between
sites-available
andsites-enabled
helps manage active and inactive site configurations easily.
Virtual Host Configuration Fundamentals
Virtual hosts in NGINX are defined using server blocks. These blocks specify domain names, document roots, and other settings.
Basic Configuration File Structure
Main NGINX Configuration File (
nginx.conf
):http { # Global settings include mime.types; # Include file type mappings default_type application/octet-stream; sendfile on; # Optimize file transfers keepalive_timeout 65; # Keep-alive timeout duration # Include virtual host files include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
- Explanation: This is the core configuration structure where global settings and virtual host files are included.
Creating Your First Virtual Host
Create a New Virtual Host File:
sudo nano /etc/nginx/sites-available/example.com
- Explanation: Opens a text editor to create a new configuration file for
example.com
.
- Explanation: Opens a text editor to create a new configuration file for
Add Basic Virtual Host Configuration:
server { listen 80; # Listen on port 80 (HTTP) server_name example.com www.example.com;# Define domain names root /var/www/example.com; # Set the document root index index.html index.htm; # Specify default index files location / { try_files $uri $uri/ =404; # Serve files or return 404 if not found } # Logging access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; }
- Explanation: Defines where the website files are located and how requests should be handled.
Enable the Virtual Host:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
- Explanation: Creates a symbolic link to activate the configuration.
Test NGINX Configuration:
sudo nginx -t
- Explanation: Checks for syntax errors in the configuration files.
Reload NGINX:
sudo systemctl reload nginx
- Explanation: Applies the new configuration without interrupting existing connections.
Server Blocks Configuration
Setting Up Multiple Domains
To host multiple websites on the same server, configure multiple server blocks.
# Configuration for example.com
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP configuration for example.com
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
# Configuration for blog.example.com
server {
listen 80;
server_name blog.example.com;
root /var/www/blog.example.com;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
}
- Explanation: Defines two separate server blocks for
example.com
andblog.example.com
. Each block has its own root directory and settings.
Configuring Subdomains
Subdomains are treated as separate server blocks.
server {
listen 80;
server_name subdomain.example.com;
root /var/www/subdomain.example.com;
location / {
proxy_pass http://localhost:3000; # Forward requests to a backend server
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
- Explanation: Useful for applications running on different ports or backends.
Advanced Virtual Host Configurations
URL Rewriting
URL rewriting can be used to redirect old URLs to new ones or create cleaner URLs.
server {
listen 80;
server_name example.com;
location / {
rewrite ^/old-page$ /new-page permanent; # Permanent redirect
rewrite ^/blog/(\d{4})/(\d{2})/(.*)$ /blog/$3 last;
}
}
- Explanation: The
rewrite
directive handles URL transformations.
Load Balancing
Load balancing distributes incoming requests across multiple servers.
upstream backend_servers {
least_conn; # Use least connections method
server backend1.example.com:8080;
server backend2.example.com:8080;
server backend3.example.com:8080 backup; # Backup server
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_servers; # Forward to backend servers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
- Explanation: The
upstream
block defines a group of backend servers.least_conn
distributes traffic to the server with the fewest connections.
Caching
Caching improves performance by storing frequently accessed content.
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m;
server {
listen 80;
server_name example.com;
location / {
proxy_cache my_cache;
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
proxy_cache_valid 200 60m;
proxy_pass http://backend;
}
}
}
- Explanation: Configures a caching zone to store and serve cached content.
SSL/TLS Configuration
Basic SSL Configuration
Secure your site with SSL/TLS encryption.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt; # SSL certificate
ssl_certificate_key /etc/nginx/ssl/example.com.key; # SSL key
ssl_protocols TLSv1.2 TLSv1.3; # Only use secure protocols
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000" always;
}
- Explanation: Configures SSL/TLS with strong encryption and HSTS for security.
HTTP to HTTPS Redirect
Redirect all HTTP traffic to HTTPS.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
- Explanation: Ensures all traffic is encrypted by redirecting to HTTPS.
Troubleshooting and Common Issues
Analyzing Logs
Logs provide insights into server behavior and help diagnose issues.
# View error logs
sudo tail -f /var/log/nginx/error.log
# View access logs
sudo tail -f /var/log/nginx/access.log
- Explanation: Use these commands to monitor NGINX logs in real-time.
Common Issues and Solutions
502 Bad Gateway
- Cause: The backend server (e.g., PHP-FPM) is down or misconfigured.
- Solution:
location ~ \.php$ { fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; }
- Explanation: Adjusts buffer sizes to avoid communication issues.
413 Request Entity Too Large
- Cause: The client is trying to upload a file that exceeds the default limit.
- Solution:
client_max_body_size 100M;
- Explanation: Increases the maximum allowable upload size.
Best Practices and Security
Implementing Security Headers
Security headers help protect your site from various attacks.
server {
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self'" always;
}
- Explanation: These headers prevent clickjacking, XSS, and other attacks.
Rate Limiting
Rate limiting prevents abuse by controlling the number of requests from a client.
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location /login {
limit_req zone=one burst=5;
}
}
}
- Explanation: Limits requests to one per second with a burst allowance of five.
Performance Optimization
Enabling Gzip Compression
Compressing responses reduces bandwidth usage.
http {
gzip on;
gzip_vary on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml application/json application/javascript;
}
- Explanation: Enables Gzip compression for specified content types.
Browser Caching
Leverage browser caching to improve performance.
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
- Explanation: Sets cache expiration for static assets.
Optimizing Worker Processes
Configure worker processes based on your server's CPU cores.
worker_processes auto; # Automatically detects the number of CPU cores
events {
worker_connections 1024; # Number of simultaneous connections per worker
multi_accept on; # Accept multiple connections at once
}
- Explanation: Ensures efficient handling of connections.
Conclusion
This guide has covered the essentials and advanced concepts of NGINX virtual host configuration. You now understand how to:
- Set up basic and advanced virtual host configurations
- Implement SSL/TLS for secure communications
- Troubleshoot common issues
- Follow best practices for security and performance
Final Tips
- Regularly Monitor Your Server: Keep an eye on logs and server performance.
- Keep NGINX Updated: Install the latest security patches.
- Document Your Configurations: Maintain organized and well-documented configuration files.
- Optimize Based on Needs: Tailor configurations to your specific requirements.
NGINX is a highly flexible and robust tool that can be customized for various scenarios. For advanced configurations and features, refer to the official NGINX documentation.