Nginx HTTPS Redirect Configuration
Redirect all HTTP traffic to HTTPS in Nginx using a 301 permanent redirect. Covers www to non-www canonical URL handling and HSTS preloading setup.
Detailed Explanation
Redirecting HTTP to HTTPS ensures all visitors use an encrypted connection. A 301 permanent redirect tells browsers and search engines that the HTTPS version is the canonical URL, which is important for SEO.
Simple HTTP to HTTPS Redirect
The cleanest approach uses a dedicated server block listening on port 80 that returns a 301 redirect for all requests. This is the recommended method.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
Canonical URL (www vs non-www)
For SEO purposes, you should pick one canonical form and redirect the other to it. This example redirects both HTTP and www to the non-www HTTPS version, consolidating all link equity on a single URL:
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
return 301 https://example.com$request_uri;
}
Why Use return Instead of rewrite
The return 301 directive is more efficient than rewrite for simple redirects because it does not require regular expression evaluation. Nginx processes the return directive immediately without scanning through additional location blocks, resulting in less CPU overhead per request.
Preserving Query Strings
The $request_uri variable includes the original path and query string intact. This ensures that a request to http://example.com/page?id=5 correctly redirects to https://example.com/page?id=5 without losing any parameters. This is critical for preserving functionality and tracking parameters during the migration.
HSTS Header
After confirming your HTTPS setup works correctly, add the Strict-Transport-Security header to instruct browsers to always use HTTPS for your domain. This eliminates the redirect round-trip entirely for repeat visitors and protects against SSL stripping attacks.
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
Testing Your Redirects
Always test redirects with curl -I http://example.com to verify the 301 status code and the Location header value before deploying to production. Incorrect redirect configurations can cause redirect loops that render your entire site inaccessible to visitors and search engine crawlers.
Use Case
You are migrating your website from HTTP to HTTPS and need to ensure all existing links, bookmarks, and search engine indexes seamlessly redirect to the secure version.