How to force or redirect to SSL in nginx?

Better Stack Team
Updated on November 9, 2023

To force or redirect all incoming traffic to SSL (HTTPS) in Nginx, you can use a server block that handles HTTP requests on port 80 and redirect them to HTTPS. 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 HTTP traffic and redirect it to HTTPS. Here's an example:
 
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    # Redirect all HTTP traffic to HTTPS
    return 301 https://$server_name$request_uri;
}

This configuration block listens on port 80 for HTTP traffic and uses the return 301 directive to perform a permanent (301) redirect to the HTTPS version of the same URL. Make sure to replace yourdomain.com with your actual domain name.

  1. Save the changes and exit the configuration file.
  2. After making changes, reload Nginx to apply the new configuration:
 
sudo systemctl reload nginx

This will reload the Nginx configuration, and all incoming HTTP requests to http://yourdomain.com or http://www.yourdomain.com will be automatically redirected to their HTTPS counterparts.

Remember to have the HTTPS server block also set up to handle requests on port 443 with SSL configured properly for this to work effectively.

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