Remove "www" and redirect to "https" with nginx

Better Stack Team
Updated on November 9, 2023

To remove the "www" from URLs and redirect all incoming traffic to HTTPS in Nginx, you can use a server block that handles both scenarios. Here's an example configuration:

  1. Open your Nginx configuration file for your site (commonly found at /etc/nginx/sites-available/yoursite or /etc/nginx/nginx.conf).
  2. Add or modify a server block to handle the redirection. Here's an example:
 
server {
    listen 80;
    server_name www.yourdomain.com;

    # Redirect www to non-www and to HTTPS
    return 301 https://yourdomain.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.yourdomain.com;

    # Redirect www to non-www and to HTTPS
    return 301 https://yourdomain.com$request_uri;
}

server {
    listen 443 ssl;
    server_name yourdomain.com;

    # Your regular HTTPS server block configuration goes here
    # ...

    # Rest of your SSL configuration for yourdomain.com
    # include SSL certificate, key, SSL protocols, etc.
    # ...
}

In this configuration:

  • The first two server blocks handle HTTP and HTTPS requests for www.yourdomain.com and redirect to https://yourdomain.com.
  • The third server block handles HTTPS requests for yourdomain.com and should contain your regular site configuration for handling HTTPS traffic.
  • Save the changes and exit the configuration file.
  • After making changes, reload Nginx to apply the new configuration:
 
sudo systemctl reload nginx

This will redirect both http://www.yourdomain.com and https://www.yourdomain.com to https://yourdomain.com.

Ensure you have the appropriate SSL configurations and certificates set up for yourdomain.com in the last server block to handle HTTPS traffic. Adjust the server_name and SSL configurations according to your specific setup.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github