HackerPost

LINUX
UBUNTU
GITHUB
TECHNOLOGY
NGINX

Redirect www traffic to non www with ubuntu and nginx

Time Spent- 20m
177 Visitors

While working on a project, I realized this is a common issue with developers.


1. Edit Nginx configuration:

There are two main approaches depending on your setup:

  • A. Existing server block:

If you already have a server block configured for your domain in /etc/nginx/sites-available/ or /etc/nginx/conf.d/, you can modify it to include the redirect.

  • B. New server block:

If you don't have a server block for your domain yet, you'll need to create a new one.


2. Adding the redirect code:

Here's the code to add to your server block configuration file:

Nginx

server {
  # Existing server_name configuration (if applicable)
  server_name www.yourdomain.com;

  # Add a redirect for www traffic
  rewrite ^/(.*) http://yourdomain.com/$1 permanent;

  # Rest of your server block configuration (location blocks, etc.)
}

Replace:

  • yourdomain.com with your actual domain name.

Explanation:

  • server_name www.yourdomain.com; : This line defines the server block for the www subdomain.
  • rewrite ^/(.*) http://yourdomain.com/$1 permanent; : This line rewrites any request starting with "/" (everything after www.yourdomain.com [invalid URL removed]) to the non-www version (http://yourdomain.com/$1) and sets the redirect status code to 301 (permanent).


3. Save and reload Nginx:

  • Once you've added the code, save the configuration file.
  • Test the configuration for syntax errors: sudo nginx -t
  • If there are no errors, reload Nginx: sudo systemctl reload nginx


4. Verify the redirect:

Open your website with the www prefix (e.g., [invalid URL removed]) in your browser. You should be automatically redirected to the non-www version ([invalid URL removed]).

Additional notes:

  • You can also use https instead of http in the redirect URL if you have an SSL certificate configured.
  • Consider creating a new server block for the non-www domain for better organization, especially if you don't have one already.