如何在App Engine Flex上将HSTS标头添加到我的Nginx / react应用?

时间:2018-09-01 21:15:59

标签: reactjs nginx app-engine-flexible hsts

我有一个使用自定义域和SSL,在应用程序引擎灵活的环境中通过nginx运行的react应用程序,我想添加HSTS标头。

我知道从哪些资源中我可以发现我的应用程序代码本身需要提供标头,而不是直接将它们放在任何app.yaml文件中,

所以我认为我可以按照https://www.nginx.com/blog/http-strict-transport-security-hsts-and-nginx/

中的说明通过nginx.conf来做到这一点。

但是,我的nginx块专门用于响应应用引擎请求,因此它实际上仅在监听:8080-

给我的印象是,所有请求都从应用程序引擎传递到:8080,所以我无法想象添加另一个服务器块来监听443会做什么?

也许我最好让react应用程序以某种方式服务标题吗?

worker_processes 1;

events {
  worker_connections 1024;
}

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  # Logs will appear on the Google Developer's Console when logged to 
this
  # directory.
  access_log /var/log/app_engine/app.log;
  error_log /var/log/app_engine/app.log;

  gzip on;
  gzip_disable "msie6";

  server {
    listen 8080;

    server_name localhost;
    root /src/build;

    if ( $http_x_forwarded_proto = 'http' ) {
      return 301 https://$host$request_uri;
    }

    location /nginx_status {
      stub_status on;
      access_log off;
    }

    location / {
      try_files $uri $uri/ /index.html;
    }
  }
}

1 个答案:

答案 0 :(得分:2)

好吧,现在我觉得很愚蠢。

我要做的就是在正确的位置添加以下行:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

最初,我尝试将其添加到if ( $http_x_forwarded...部分的上方,并且还尝试使用末尾的always关键字,并且我的部署在此行中一直失败。 / p>

无论如何,它有效!

完整的nginx.conf结果如下:

worker_processes 1;

events {
  worker_connections 1024;
}

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  # Logs will appear on the Google Developer's Console 
  # when logged to this directory.
  access_log /var/log/app_engine/app.log;
  error_log /var/log/app_engine/app.log;

  gzip on;
  gzip_disable "msie6";

  server {
    listen 8080;

    server_name localhost;
    root /src/build;

    if ( $http_x_forwarded_proto = 'http' ) {
      return 301 https://$host$request_uri;
    }

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";        

    location /nginx_status {
      stub_status on;
      access_log off;
    }

    location / {
      try_files $uri $uri/ /index.html;
    }
  }
}