Setting Up HTTPS Redirect on Nginx: A Simple Guide

Author:Lars Nyström
Updated:Mar 22, 2025

In today's digital landscape, securing your website with HTTPS is not just a recommendation—it's a necessity. HTTPS ensures that data transmitted between your site and users is encrypted, protecting sensitive information like credit card details and login credentials. Implementing an automatic HTTPS redirect can help ensure that all users connect securely, even if they accidentally use the unencrypted HTTP protocol.

This guide will walk you through setting up an HTTPS redirect on a Nginx web server, covering various scenarios to meet your needs.

Why HTTPS Redirects Are Important

  • Security: Encrypts data in transit, safeguarding against eavesdropping.
  • Trust: Users are more likely to trust sites that use HTTPS, enhancing your site's credibility.
  • Compliance: Many websites and services now require HTTPS for API integrations and user logins.

Understanding Nginx Directives

Nginx uses directives to configure behavior. The return directive is particularly useful for immediate redirects. It allows you to specify the status code, the redirect location, and the content body in one line.

Syntax Example:

return 301 https://$host$request_uri;

This directive tells Nginx to return a 301 (permanent) redirect to https:// version of the current host with the same request URI.

Configuring HTTPS Redirects

1. Redirecting an Entire Site

If you want all traffic to your site to use HTTPS, modify your default server block in your Nginx configuration file (nginx.conf or a site-specific config file).

server {
    listen 80;
    server_name example.com;

    location / {
        return 301 https://$host$request_uri;
    }
}

This redirects all requests to https://example.com.

2. Redirecting Specific Directories

If you only want certain directories to use HTTPS, use the location directive.

location ^~ /test/ {
    return 301 https://example.com$request_uri;
}

This redirects any request to /test/ or files within it to https://example.com.

3. Redirecting a Single Page

To redirect a specific file, like index.html, use the following:

location ^~ /index.html {
    return 301 https://example.com;
}

This ensures that when users request index.html, they are redirected to https://example.com.

4. Custom Redirects

For more complex redirects, you can include additional parameters.

return 301 https://new.example.com/path/old-page.html;

This redirects http://old.example.com/path/old-page.html to https://new.example.com/path/old-page.html.

Best Practices

  • Test: After implementing, test the redirect by accessing your site via HTTP and ensuring it switches to HTTPS.
  • Clear Message: Use a clear error message for users if the redirect fails initially.
  • Compliance: Ensure that all subdomains are covered in your configuration.