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.
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.
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.
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.
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.
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.
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.