How to properly redirect subdomains in nginx?

Member

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

How to properly redirect subdomains in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jewel , 3 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.