How to Redirect HTTP to HTTPS in Nginx: Simple Guide
To redirect
http traffic to https in Nginx, use a server block listening on port 80 with a return 301 https://$host$request_uri; directive. This sends a permanent redirect to the HTTPS version of the requested URL.Syntax
The basic syntax to redirect HTTP to HTTPS in Nginx involves creating a server block that listens on port 80 (HTTP) and uses the return directive to send a 301 redirect to the HTTPS URL.
server {}: Defines a server block.listen 80;: Listens on HTTP port 80.server_name: Specifies the domain name(s) to match.return 301 https://$host$request_uri;: Sends a permanent redirect to the HTTPS version of the requested URL.
nginx
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}Example
This example shows a complete Nginx configuration snippet that redirects all HTTP requests to HTTPS for the domain example.com and www.example.com. When a user visits http://example.com/page, they are redirected to https://example.com/page.
nginx
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
location / {
root /var/www/html;
index index.html;
}
}Output
When accessing http://example.com/page, the browser receives a 301 redirect to https://example.com/page.
Common Pitfalls
Common mistakes when redirecting HTTP to HTTPS in Nginx include:
- Forgetting to specify
listen 80;in the redirect server block, so it doesn't catch HTTP requests. - Using
rewriteinstead ofreturn 301, which is less efficient for simple redirects. - Not including all domain variants in
server_name, causing some requests to not redirect. - Missing SSL certificate configuration in the HTTPS server block, leading to SSL errors.
Example of a wrong and right redirect:
nginx
server {
listen 80;
server_name example.com;
# Wrong: Using rewrite for redirect
rewrite ^ https://$host$request_uri? permanent;
}
server {
listen 80;
server_name example.com;
# Right: Using return for redirect
return 301 https://$host$request_uri;
}Quick Reference
Summary tips for HTTP to HTTPS redirection in Nginx:
- Use
return 301 https://$host$request_uri;for efficient permanent redirects. - Listen on port 80 in the redirect server block.
- Include all domain names in
server_name. - Configure SSL certificates properly in the HTTPS server block.
Key Takeaways
Always use a server block listening on port 80 with a return 301 directive to redirect HTTP to HTTPS.
Use the syntax return 301 https://$host$request_uri; for a clean and efficient redirect.
Include all your domain names in the server_name directive to cover all requests.
Configure SSL certificates correctly in the HTTPS server block to avoid errors.
Avoid using rewrite for simple redirects; return is faster and clearer.