将所有http重定向到nginx中的https,但一个文件除外

时间:2011-12-08 04:50:48

标签: http ssl https nginx redirect

我目前正在http上运行我的网站,并希望将其移至https,以便nginx自动处理重定向。我猜这是非常微不足道的。

但是,有一个文件(由于多种原因)与其他网站热链接,其中一些是通过http而一些通过https。我想确保该文件可通过http和https使用,以确保浏览器不会抱怨“混合内容”对话框。该文件的路径如下所示:

HTTP(S)://mydomain.com/scripts/ [some_sha1_hash] /file.js

因此,nginx规则应该说:“如果请求已经通过https,一切都很好,只需反向代理它。否则,将所有请求从http重定向到https,除非请求这一个文件,哪种情况下不做任何这样的http-> https重定向。“

任何人都可以告诉我在哪里学习这样的配置,或者帮我配置本身?提前致谢。 (对不起,但我在nginx配置上还不够熟练。)

3 个答案:

答案 0 :(得分:6)

这就是我所做的,有效:

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;
    }
}

这个只处理http请求并提供所述文件 - 否则重定向到https。定义您的ssl服务器块,它将为所有https请求提供服务。

server {
   listen         443;
   server_name    example.com;

   ssl            on;

  # rest of the config
}

这样,您的脚本文件将在http和https上提供。

答案 1 :(得分:4)

试试这个:

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
  }
}

答案 2 :(得分:-2)

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;

   [....]
}

如果我没错,上面应该主要做的伎俩

相关问题