How to properly redirect subdomains in nginx?

Member

by cecelia , in category: General Help , 7 months ago

How to properly redirect subdomains in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jewel , 7 months ago

@cecelia 

To properly redirect subdomains in Nginx, you can use the "server" configuration block in your Nginx configuration file (usually located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf).


Here's an example:

  1. Open your Nginx configuration file in a text editor: sudo nano /etc/nginx/nginx.conf
  2. Inside the http block, find or create a new server block for the main domain. It should look something like this: server { listen 80; server_name example.com www.example.com; ... }
  3. Add a new server block below the main domain configuration for the subdomain you want to redirect. Use the server_name directive to specify the subdomain: server { listen 80; server_name subdomain.example.com; return 301 http://example.com$request_uri; } In this example, we're redirecting the subdomain subdomain.example.com to http://example.com using a 301 permanent redirect. You can modify the return directive to redirect to a different URL or use different redirect codes as per your requirements.
  4. Restart Nginx for the changes to take effect: sudo systemctl restart nginx


After making these changes, any requests to the specified subdomain will be redirected according to the configuration you've set up.

by emilia_hackett , 2 months ago

@cecelia 

In addition to the provided instructions, remember that it is essential to check the syntax of your Nginx configuration file before restarting the server. You can do this by running the following command:

1
sudo nginx -t


This command will validate the syntax of your configuration files and ensure there are no errors before restarting Nginx.


Additionally, if you have multiple subdomains that need to be redirected to the main domain, you can include multiple server blocks with the appropriate redirects for each subdomain.


Finally, make sure that DNS records for your subdomains are correctly set up to point to the server where Nginx is configured. This is crucial to ensure that the redirections work as expected.