Remove unnecessary HTTP headers in my rails answers

后端 未结 3 1722
眼角桃花
眼角桃花 2021-01-12 22:44

I am currently developing an API where size matters: I want the answer to contain as few bytes as possible. I optimized my JSON answer, but rails still responds with many st

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 23:46

    I agree that both solutions presented by x1a4 and Stephen McCarth are good.

    Ideally you should definitely use the HttpHeadersMoreModule however if someone is fan of native Ubuntu NginX package with security updates like I am, (or you don't have time for that, or just lazy) you don't necessary need to do that.

    Another way is to use proxy_hide_header

    server {
    
      location @unicorn {
    
        # ...
        proxy_hide_header X-Powered-By;
        proxy_hide_header X-Runtime;
        # ...
      }
    }
    

    note: @unicorn is just upsteram server, the location can be whatever /, /assets, ..

    Now one argument against this solution is if you use several server blocks inside configuration that you need to specify proxy_hide_header to each one of them. Well yes but you can just create file and include it

    # /etc/nginx/sites-enabled/my_app
    server {
    
      location @unicorn {
    
        # ...
        include /etc/nginx/shared/stealth_headers
        # ...
      }
    }
    
    # /etc/nginx/shared/stealth_headers
    proxy_hide_header X-Powered-By;
    proxy_hide_header X-Runtime    
    

    So why I think this solution is better than to use the middle-ware solution as presented by x1a4 ?

    I had similar middle-ware solution before and it was working fine for couple of months. Then one day we stopped receiving Exception errors by exception monitoring tool party_foul gem. Long story short Middlewares are tricky, we done some code changes and this middleware was throwing exception, but it was throwing exception that was not caught with middleware that was suppose to monitor exceptions. So yes the whole thing is my bad, I should keep better eye on my code not doing stupid stuff, hewever I had unpleasant experience that is hard to erase, so I'm just recommending if you can rather to handle this on NginX level, not on middle-ware level

    + it make more sence if your NginX is handling several configurations (you don't have to update several applications if some change)

提交回复
热议问题