Introduction
Web applications often require multiple subdomains to separate different services, applications, or environments. For example, a SaaS platform might use app.example.com for the main application, dashboard.example.com for user dashboards, api.example.com for backend services, and www.example.com for the marketing website.
Nginx, the popular open-source web server, provides robust capabilities for handling multiple subdomains on a single server through its server blocks (also known as virtual hosts) feature.
This comprehensive guide walks you through configuring Nginx to serve multiple subdomains, including reverse proxy setup, SSL certificate installation, and security configurations. Whether you're setting up a multi-tenant application, separating development and production environments, or simply organizing different services under your domain, mastering subdomain configuration with Nginx is an essential skill for web developers and DevOps engineers. For complex multi-subdomain architectures, our /services/web-development/ team can help design and implement scalable solutions.
Understanding Subdomains and Their Use Cases
A subdomain is a prefix that appears before your main domain name, separated by a dot. While example.com represents your primary domain, app.example.com, blog.example.com, and shop.example.com are all subdomains of the main domain. Subdomains function as independent websites that can host different content, applications, or services while sharing the same root domain and, in many cases, the same server infrastructure.
Primary Use Cases for Multiple Subdomains
- Service Isolation: Different components of your application run independently (separating frontend from backend API)
- Multi-Tenant Architecture: Each tenant receives a unique subdomain (
tenant1.example.com,tenant2.example.com) - Environment Separation: Distinguish between development (
dev.example.com), staging (staging.example.com), and production (app.example.com) - Brand Segmentation: Create distinct experiences for different product lines
Planning Your Subdomain Strategy
When planning your subdomain strategy, consider how users will interact with each subdomain, whether they need to share authentication or session data across subdomains (which requires specific cookie configuration), and how DNS propagation will affect your rollout timeline. Understanding these factors helps you design a configuration that's both functional and maintainable over time.
Related services that support subdomain architectures include our cloud infrastructure services and API development services, which often work alongside Nginx configurations to deliver complete solutions.
DNS Configuration for Subdomains
Before configuring Nginx, you must properly set up DNS records to point your subdomains to your server's IP address. DNS (Domain Name System) acts as the internet's address book, translating human-readable domain names into IP addresses that computers use to communicate. Without correct DNS configuration, browsers cannot find your subdomain servers, regardless of how well you've configured Nginx.
A Records for Subdomains
An A record maps a domain name directly to an IPv4 address. For subdomains, you create A records that point the subdomain prefix to your server's public IP address. If your server has the IP address 192.0.2.100, you would create A records for each subdomain: app.example.com → 192.0.2.100, api.example.com → 192.0.2.100, and dashboard.example.com → 192.0.2.100. Most DNS providers allow you to create these records through their web interface, and propagation typically takes anywhere from a few minutes to 48 hours, though it often completes within a few hours for most locations.
CNAME Records for Subdomains
A CNAME (Canonical Name) record creates an alias that points one domain name to another. Instead of pointing directly to an IP address, a CNAME points to another domain name. This is useful when you want a subdomain to always follow the same destination as your main domain, simplifying management when your server IP changes. For example, you could create www.example.com as a CNAME pointing to example.com. However, be aware that CNAME records cannot coexist with other records for the same name, so you typically cannot have both an A record and a CNAME for the same subdomain.
Wildcard Subdomain Records
For applications that dynamically create subdomains, such as multi-tenant platforms, you can create a wildcard DNS record. An A record with *.example.com pointing to your server IP will catch any subdomain that doesn't have a more specific record. This approach eliminates the need to create DNS records for each new subdomain as your application adds tenants or users.
As explained in HostAdvice's DNS configuration guide, proper DNS setup is the foundation for any subdomain deployment.
Nginx Server Blocks for Subdomain Configuration
Nginx's server blocks allow you to define separate configurations for different domains or subdomains on a single server. Each server block acts as an independent virtual host, with its own document root, logging, and directives. When Nginx receives a request, it examines the Host header to determine which server block should handle it, enabling efficient hosting of multiple subdomains from one installation.
Creating Server Block Configuration Files
Nginx configuration files typically reside in /etc/nginx/sites-available/ for available sites and /etc/nginx/sites-enabled/ for currently active configurations. Create a separate configuration file for each subdomain, using descriptive filenames that make the purpose clear: app.example.com.conf, api.example.com.conf, and dashboard.example.com.conf. This organization makes it easier to manage configurations as your subdomain portfolio grows.
Basic Server Block Example
server {
listen 80;
listen [::]:80;
server_name app.example.com www.app.example.com;
root /var/www/app.example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
Key Directives
- listen: Ports Nginx should listen on (80 for HTTP, 443 for HTTPS)
- server_name: Hostnames this block should respond to
- root: Document root directory for static files
- index: Default index files
As documented in LogRocket's Nginx subdomain guide, properly configured server blocks form the foundation of multi-subdomain deployments.
Reverse Proxy Configuration for Backend Services
Many modern web applications use subdomains to access different backend services, such as API servers, application servers, or microservices. Rather than serving static files, Nginx can act as a reverse proxy, forwarding requests to backend services running on different ports or different servers entirely. This architecture is fundamental to microservices deployments and provides benefits including centralized SSL termination, load balancing across multiple backend instances, caching of frequently accessed content, and protection of backend services from direct internet access.
Basic Reverse Proxy Setup
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Essential Proxy Headers
The proxy_set_header directives are crucial for maintaining proper request information as requests pass through the proxy:
proxy_set_header Host $host: Preserves the original hostnameproxy_set_header X-Real-IP $remote_addr: Client's actual IP addressproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for: Full proxy chainproxy_set_header X-Forwarded-Proto $scheme: Original protocol (HTTP/HTTPS)
Load Balancing Across Multiple Backends
upstream api_servers {
least_conn;
server 10.0.0.1:3000;
server 10.0.0.2:3000;
}
server {
location / {
proxy_pass http://api_servers;
}
}
For high-availability deployments, Nginx can distribute requests across multiple backend servers using its upstream module. This setup pairs well with our container orchestration services for production-grade deployments.
SSL Certificate Setup with Let's Encrypt and Certbot
Securing your subdomains with SSL certificates is essential for protecting user data, improving search engine rankings, and enabling modern web features. Let's Encrypt provides free, automated SSL certificates that have become the standard for subdomain security. Certbot is the recommended tool for obtaining and managing these certificates, with plugins that can automatically configure Nginx for SSL.
Installing Certbot
sudo apt install certbot python3-certbot-nginx
Obtaining SSL Certificates
sudo certbot --nginx -d app.example.com -d api.example.com -d dashboard.example.com
Certbot can obtain certificates for multiple subdomains in a single command, reducing overhead and ensuring all certificates are managed together. When prompted, select whether to redirect HTTP traffic to HTTPS automatically.
Certificate Renewal
Let's Encrypt certificates are valid for 90 days, requiring regular renewal. Certbot automatically sets up a systemd timer to handle renewal attempts twice daily:
# Test renewal
sudo certbot renew --dry-run
# Manual renewal
sudo certbot renew
As outlined in the OneWorldCoders SSL setup guide, automated certificate management is essential for production deployments.
HTTP to HTTPS Redirection Configuration
Ensuring all traffic uses encrypted HTTPS connections requires explicit configuration to redirect HTTP requests. Without redirection, users who manually type http:// or follow old HTTP links would connect without encryption. Proper redirection guarantees that all communication with your subdomains is encrypted, protecting against eavesdropping and man-in-the-middle attacks.
Server Block for HTTP Redirect
server {
listen 80;
listen [::]:80;
server_name app.example.com www.app.example.com;
return 301 https://$host$request_uri;
}
This configuration uses a 301 (permanent) redirect, which indicates to browsers and search engines that the redirect is permanent. The $host variable preserves the original hostname while $request_uri maintains the complete request path.
WWW to Non-WWW Redirect
server {
listen 443 ssl;
server_name www.app.example.com;
ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
return 301 https://app.example.com$request_uri;
}
Security Headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
Implementing proper security headers protects against common web vulnerabilities and is a critical component of any web security strategy.
Testing and Troubleshooting Subdomain Configurations
After configuring Nginx for multiple subdomains, thorough testing ensures everything works as expected. Testing should verify DNS resolution, HTTP/HTTPS connectivity, correct content serving, and proper redirect behavior.
Configuration Syntax Validation
sudo nginx -t
sudo systemctl reload nginx
Always validate your configuration syntax before reloading. This command checks all configuration files for syntax errors and reports any issues with line numbers.
Command-Line Testing
# Check redirect behavior
curl -I http://app.example.com
# Follow redirects
curl -L http://app.example.com
# Check SSL certificate
openssl s_client -connect app.example.com:443 -servername app.example.com
Common Issues and Solutions
| Issue | Solution |
|---|---|
| 404 error | Verify document root path and permissions |
| Redirect loops | Check for conflicting redirect rules |
| SSL errors | Ensure port 80 is open for Let's Encrypt validation |
| Mixed content | Use HTTPS URLs for all resources |
Performance Optimization
worker_processes auto;
worker_connections 1024;
keepalive_timeout 65;
gzip on;
These settings ensure Nginx handles traffic efficiently. For additional performance tuning, consider our DevOps consulting services.
Best Practices for Production Subdomain Deployments
Production deployments require attention to security, performance, and maintainability beyond basic functionality. Implementing best practices ensures your subdomain configuration is robust, efficient, and manageable over time.
Security Best Practices
- Always use HTTPS: Redirect all HTTP to HTTPS
- Implement HSTS:
max-age=31536000; includeSubDomains - Configure CSP headers: Control resource loading
- Keep certificates renewed: Monitor expiration dates
Performance Best Practices
- Enable gzip compression: Reduce bandwidth usage
- Configure caching: Set appropriate expires headers
- Use keepalive connections: Reduce connection overhead
- Monitor with separate logs: Debug issues quickly
Maintainability Best Practices
- Version control configurations: Track changes over time
- Document subdomain strategy: Explain purpose and backend routing
- Use templates: Generate configs dynamically for similar subdomains
- Regular testing: Verify all subdomains respond correctly
Configuration Management
Consider using configuration management tools like Ansible, Puppet, or Terraform for:
- Repeatable deployments across environments
- Automated certificate management
- Centralized configuration backup
- Rollback capabilities
These practices align with enterprise-grade cloud infrastructure solutions for scalable deployments.
Conclusion
Configuring Nginx to handle multiple subdomains provides a powerful foundation for hosting complex web applications, multi-tenant platforms, or simply organizing different services under a unified domain. By properly setting up DNS records, creating dedicated server blocks, configuring reverse proxy forwarding, and securing everything with SSL certificates, you build a robust infrastructure that scales with your needs.
The key steps covered in this guide include:
- Proper DNS configuration with A records, CNAME records, or wildcard records
- Dedicated server blocks for each subdomain with correct document roots
- Reverse proxy setup for routing to backend services
- SSL certificate installation using Let's Encrypt and Certbot
- HTTP to HTTPS redirection for secure communications
- Comprehensive testing before deployment
With these practices in place, your multi-subdomain Nginx deployment will provide reliable, secure service for years to come. For organizations requiring ongoing server management and optimization, our managed hosting services provide comprehensive support for complex infrastructure needs.
Frequently Asked Questions
DNS Configuration
Proper A records, CNAME records, and wildcard records ensure subdomains resolve correctly to your server.
Nginx Server Blocks
Virtual host configurations define how each subdomain is handled, with dedicated document roots and routing rules.
Reverse Proxy Setup
Forward requests to backend services running on different ports or servers for microservices architectures.
SSL/TLS Security
Let's Encrypt certificates and automated renewal ensure all subdomains are secured with HTTPS.