Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect all http to https in nginx, except one file

I am currently running my site on http, and want to move it over to https such that nginx handles the redirection automagically. This is fairly trivial to do, I guess.

However, there is one file that (for several reasons) is hot-linked from other sites, some of which are over http and some over https. I want to ensure that the file is available over both http and https, so as to ensure that browsers don't complain with the "mixed content" dialog. The path of the file looks something like this:

http(s)://mydomain.com/scripts/[some_sha1_hash]/file.js

So, the nginx rule should say: "If the request is already over https, everything is sweet, and just reverse-proxy it. Otherwise, redirect all requests from http to https, except if this one file is requested, in which case don't do any such http->https redirect."

Can anyone either tell me where to look to learn about such a config, or help me with the config itself? Thanks in advance. (I'm sorry, but I'm not skilled enough yet at nginx configuration.)

like image 257
Rakesh Pai Avatar asked Dec 08 '11 04:12

Rakesh Pai


2 Answers

This is what I did, which works:

server {
    listen 80;
    server_name example.com;
    charset     utf-8;
    access_log /var/www/path/logs/nginx_access.log;
    error_log /var/www/path/logs/nginx_error.log;

    location /path/to/script.js {
          # serve the file here
    }
    location / {
        return 301 https://example.com$request_uri;
    }
}

This one handles only http requests and serves the said file - otherwise redirects to https. Define your ssl server block, which will serve all https requests.

server {
   listen         443;
   server_name    example.com;

   ssl            on;

  # rest of the config
}

This way your script file will be available on http as well as https.

like image 136
chhantyal Avatar answered Oct 01 '22 20:10

chhantyal


Try this:

server {
  listen 80; ssl off;
  listen 443 ssl;
  server_name example.com;

  # <ssl settings>
  # ... other settings

  location = /scripts/[some_sha1_hash]/file.js {
    # Empty block catches the match but does nothing with it
  }

  location / {
    if ($scheme = "http") {
      rewrite ^ https://$http_host$request_uri? permanent;
    }

    # ... other settings
  }
}
like image 40
Seth V Avatar answered Oct 01 '22 20:10

Seth V