【问题标题】:Get NGINX to serve .gz compressed asset files with unicorn让 NGINX 为 .gz 压缩资产文件提供独角兽服务
【发布时间】:2023-10-20 18:49:01
【问题描述】:

我想在我的 nginx 和 unicorn 中激活 gzip 压缩:

我在 config/unicorn.rb:

的 rails 应用中有这个
working_directory "/home/user/project.com/current"
shared_path  = '/home/user/project.com/shared'
pid "#{shared_path}/pids/unicorn.pid"
stderr_path "#{shared_path}/log/unicorn.log"
stdout_path "#{shared_path}/log/unicorn.log"
listen '/tmp/unicorn.project.sock'
worker_processes 2
timeout 30

我的 nginx.conf 在我的 rails 应用程序中有这个:

upstream unicorn {
 server unix:/tmp/unicorn.project.sock fail_timeout=0;
}

 server {
       listen 80 default;
       root ~/project.com/current/public;
       try_files $uri/index.html $uri @unicorn;

       location @unicorn {
                           proxy_pass http://unicorn;
                         }
 error_page 500 502 503 504 /500.html;
}

我怎样才能启用这个配置,比如:

  gzip_static on;
  expires max;
  add_header Cache-Control public;

谢谢!

【问题讨论】:

    标签: deployment nginx unicorn


    【解决方案1】:

    在您的配置中添加到server { } 块:

    location ~ ^/(assets)/  {
      root /path/to/public;
      gzip_static on; # to serve pre-gzipped version
      expires max;
      add_header Cache-Control public;
    }
    

    结帐Rails guides 了解更多信息。

    【讨论】:

      【解决方案2】:

      这是我的 nginx.conf 中用于 gzip 的内容:

      gzip on;
      gzip_buffers 16 8k;
      gzip_comp_level 9;
      gzip_http_version 1.0;
      gzip_min_length 0;
      gzip_types text/plain text/css image/x-icon image/png image/jpg image/jpeg text/js text/php application/javascript application/x-javascript;
      gzip_vary on;
      gzip_proxied expired no-cache no-store private auth;
      gzip_disable     "MSIE [1-6]\.";
      

      您还可以记录 gzip 压缩:

      log_format main
              '$remote_addr - $remote_user [$time_local] '
              '"$request" $status $bytes_sent '
              '"$http_referer" "$http_user_agent" '
              '"$gzip_ratio"';
      

      【讨论】: