Redirect All Requests to HTTPS with Nginx

Assuming that you already have a working HTTPS configuration for your website and you decided to redirect all requests to HTTPS, here is a simple nginx configuration for that. This assumes that you don’t want to serve HTTP anymore.

server {
    listen 80;
    access_log off;
    error_log off;
    ## redirect http to https ##
    return      301 https://$server_name$request_uri;

This configuration will simply redirect all requests to the HTTPS version of the website and not even bother about the root paths or the proxy urls, etc. The HTTP version of the website is simply forgotten.

The redirect will honor the www and non-www version of the website.

Of course, you should already have a working HTTPS configuration for nginx, something like below.

server {
    listen 443 ssl;

    ssl on;
    ssl_certificate     /etc/nginx/certs/;
    ssl_certificate_key /etc/nginx/certs/;

    root /data/www/html/sites/;

    location ~* \.(ico|css|js|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
      expires 1y;
      add_header Cache-Control public;

      add_header ETag "";

    location / {
        proxy_redirect     off;

        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

        client_max_body_size       10m;
        client_body_buffer_size    128k;

        proxy_connect_timeout      90;
        proxy_send_timeout         90;
        proxy_read_timeout         90;

        proxy_buffer_size          8k;
        proxy_buffers              4 64k;
        proxy_busy_buffers_size    128k;
        proxy_temp_file_write_size 128k;

That’s it!

Leave a reply

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