Redirect all http to https in nginx, except one fi

2019-04-20 21:04发布

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.)

3条回答
别忘想泡老子
2楼-- · 2019-04-20 21:45

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.

查看更多
干净又极端
3楼-- · 2019-04-20 21:48

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
  }
}
查看更多
\"骚年 ilove
4楼-- · 2019-04-20 22:00
server {
   listen         80;
   server_name    my.domain.com;
   rewrite        ^ https://$server_name$request_uri? permanent;
}

server {
   listen         443;
   server_name    my.domain.com;

   ssl            on;

   [....]
}

The above should mostly do the trick if im not wrong

查看更多
登录 后发表回答