How to Configure Server Alias on Nginx Web Server
Introduction
Normally, we may need multiple domain names or subdomains to point to the same website and document root.
In Apache, we can use ServerAlias for this purpose. In Nginx, we can achieve the same functionality by adding multiple domain names to the server_name directive.
In this article, we will explain how to configure an alias domain in Nginx.
If Nginx is not installed, you can refer to the following guides:
Prerequisites
Before proceeding, make sure you have:
- Nginx installed and running
- Root or sudo access to the server
- A domain name pointing to the server
- An existing Nginx virtual host configuration
Implementation
In this example, we want both the following domains to point to the same website:
domain.tldwww.domain.tld
Step 1: Open the Nginx Configuration
If you are using the default Nginx configuration, open:
vi /etc/nginx/sites-available/default
If you have a separate configuration file for the domain, open the corresponding configuration file instead.
Step 2: Configure Server Name
You may find the following configuration:
server_name _;
Change it to:
server_name domain.tld www.domain.tld;
Multiple domain names can be added by separating them with spaces.
For example:
server_name domain.tld www.domain.tld domain.net www.domain.net;
All the configured domain names will use the same Nginx server block and document root.
Step 3: Test the Nginx Configuration
Before reloading Nginx, check the configuration for syntax errors:
nginx -t
If the configuration is correct, you should see a message similar to:
syntax is oktest is successful
Step 4: Reload Nginx
Reload Nginx to apply the changes:
service nginx reload
Alternatively:
systemctl reload nginx
Verification
Open the configured domains in a browser:
http://domain.tldhttp://www.domain.tld
Both domains should point to the same website and document root.
Conclusion
Nginx does not use the Apache ServerAlias directive. Instead, multiple domain names can be configured using the server_name directive.
By adding multiple domains to server_name, requests for those domains can be served by the same Nginx server block.
FAQ
1. What is the equivalent of Apache ServerAlias in Nginx?
Nginx uses the server_name directive to configure multiple domain names for the same server block.
2. Can I add multiple domains to server_name?
Yes. Multiple domain names can be specified with spaces:
server_name domain.tld www.domain.tld domain.net;
3. Do I need to restart Nginx after changing the configuration?
You can reload Nginx instead of restarting it:
nginx -tsystemctl reload nginx
4. What should I do if nginx -t reports an error?
Check the configuration file for syntax errors and correct them before reloading Nginx.
5. Do the domains need to point to the same server?
Yes. The DNS records for the domains should point to the Nginx server’s IP address for the configuration to work as expected.
