If you want to enforce SSL on a particular path in your application, say an admin section, you can use nginx to automatically enforce SSL. In a previous article I went over how to configure SSL, now I'll show you can redirect part of your site.

First thing is that you'll have to create two server configurations for handling the http and https traffic.

# http://example.com
server {
  server_name example.com;

  # site logging
  access_log /var/log/nginx/saywhatmom-web.access.log;
  error_log /var/log/nginx/saywhatmom-web.error.log;

  # Handle requests
  location / {
  }

  # Redirect admin requests to HTTPS
  location /api {
    return 301 https://$http_host$request_uri$is_args$query_string;
  }
}

# https://example.com
server {
  server_name example.com;

  # Site logging
  access_log /var/log/nginx/example-secure.access.log;
  error_log  /var/log/nginx/example-secure.error.log;

  # SSL
  listen 443 ssl;
  ssl_certificate     /etc/nginx/ssl/example.crt;
  ssl_certificate_key /etc/nginx/ssl/example.key;


  # Handle secure requests
  location /admin {
  }

  # Redirect normal requests back to HTTP
  location / {
    return 301 http://$http_host$request_uri$is_args$query_string;
  }
}

The first config handles http traffic. For requests of the virtual directory /admin we force a redirect. This redirect will make a request that gets picked up by the second config, which handles https traffic. If a user makes an https request outside of /admin, the second config will redirect back to the first config.

That's all there is to it.