【问题标题】:Redirect all http to https in nginx, except one file在nginx中将所有http重定向到https,除了一个文件
【发布时间】:2025-12-01 23:20:02
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: http ssl https nginx redirect


    【解决方案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 块中不包含逻辑的解决方案。
        最近更新 更多