How to Redirect All HTTP Requests to HTTPS on Nginx Web Server
I have bought a SSL certificate for my domain. How could I install this certificate and redirect all HTTP requests to HTTPS on Nginx web server?
Answer: we can easily rewrite/redirect all HTTP requests to HTTPS with Nginx web server. The syntax is as follows. We need to add the following in location or server directives:
Rewrite syntax
return 301 https://$server_name$request_uri;
Configuration file example
server {
listen 80;
server_name r00t4bl3.com;
access_log off;
error_log off;
return 301 https://$server_name$request_uri;
}
server {
listen 443 http2 ssl;
server_name r00t4bl3.com;
ssl_certificate /etc/letsencrypt/live/r00t4bl3.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/r00t4bl3.com/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
}
Reload Nginx web server
$ sudo service nginx reload
Testing
$ curl -I http://r00t4bl3.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.2
Date: Thu, 02 Nov 2017 18:13:42 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://www.r00t4bl3.com/
If the response code is 301 and the location is https, then we're set.
Final Words
I hope that you now know how to redirect all HTTP request to HTTPS on Nginx web server. If you run into any issues or have any feedback feel free to drop a comment below.