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;
        access_log off;
        error_log off;
        return      301 https://$server_name$request_uri;

    server {

        listen 443 http2 ssl;
        ssl_certificate /etc/letsencrypt/live/;
        ssl_certificate_key /etc/letsencrypt/live/;
        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


$ curl -I
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

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.



0 comment

Leave a reply

Your email address will not be published. Required fields are marked *