在nginx中将所有http重定向到https,除了一个文件

Posted

技术标签:

【中文标题】在nginx中将所有http重定向到https,除了一个文件【英文标题】:Redirect all http to https in nginx, except one file 【发布时间】:2012-01-15 14:42:13 【问题描述】:

我目前在 http 上运行我的网站,并希望将其移至 https,以便 nginx 自动处理重定向。我猜这很简单。

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

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

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

谁能告诉我在哪里可以了解这样的配置,或者帮助我了解配置本身?提前致谢。 (对不起,我对 nginx 的配置还不够熟练。)

【问题讨论】:

【参考方案1】:

这就是我所做的,它有效:

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 上可用。

【讨论】:

【参考方案2】:

试试这个:

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
  

【讨论】:

【参考方案3】:
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;

   [....]

如果我没记错的话,以上内容应该可以解决问题

【讨论】:

这看起来不会排除我想要排除的一个文件。还是我弄错了? +1 表示在 location 块中不包含逻辑的解决方案。

以上是关于在nginx中将所有http重定向到https,除了一个文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 nginx docker elastic beanstalk中将http重定向到https

在闪亮的服务器不工作的情况下,在 NGINX 中将 HTTP 重定向到 HTTPS

如何在 Laravel 4 中将一个路由重定向到 HTTPS,将所有其他路由重定向到 HTTP?

nginx重定向除一个以外的所有目录

在 Codeigniter 中将 http 重定向到 https

Nginx反向代理:将所有http请求重定向到https