Monday, November 28, 2011

How to rewrite all to https in nginx

Here we are going redirect all http traffic to https with nginx. I suppose you already have nginx installed, if not have a look here. We will store SSL certificates in /etc/nginx/ssl directory.
cd /etc/nginx
mkdir ssl
openssl req -new -x509 -sha256 -days 9999 -nodes \
    -out ssl/cert.pem -keyout ssl/cert.key
chown -R www-data:www-data ssl
chmod -R 700 ssl
Here is nginx configuration:
upstream backend {
    server 127.0.0.1:8080;
}

server {
    listen  *:80;
    return 301 https://$host$request_uri;
    #if ( $scheme = "http" ) {
    #    rewrite  ^/(.*)$  https://$host/$1 permanent;
    #}
}

server {
    listen  *:443;

    ssl on;
    ssl_protocols TLSv1;
    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/cert.key;

    location / {
        proxy_pass http://backend;
    }
}
You have to reload nginx so the changes take place.

5 comments :

  1. Thanks for posting this. I recently merged http/https sections and couldn't recall the syntax for checking whether a request was via http and https and Google brought me here.

    Thanks again.

    ReplyDelete
  2. Your example is very expensive in terms of resources, because every single request which comes in needs to go through the "if" statement. I would do like:

    return 301 https://$server_name$request_uri;

    ReplyDelete
    Replies
    1. In both cases there is issued permanent redirect, thus browser is instructed to use https location forward. I have updated post with nginx return directive.

      Delete
  3. The return rocks. Thanks. But for somehow I have to put server_name for the server *:80 to make it work...

    ReplyDelete