使用rails应用程序将http重定向到nginx中的https

时间:2018-05-31 04:35:49

标签: ruby-on-rails nginx

我想自动将http重定向到https。

以下是我的nginx conf。

upstream puma_tn{
#   Path to Puma SOCK file, as defined previously
 server unix:/home/deploy/tn/shared/tmp/sockets/tn-puma.sock fail_timeout=0;
}

server {

  listen 80;

  server_name www.tn.com.au;

#return 301 https://$host$request_uri;
  return 301 https://$server_name$request_uri;
#if ($scheme = http) {
#        return 301 https://$server_name$request_uri;
#    }
}
server {
  listen 443 default_server ssl;
  server_name www.tn.com.au;



  root /home/deploy/tn/current/public;

  try_files $uri/index.html $uri @app;

  ssl_certificate           /etc/ssl/certs/tn.crt;
    ssl_certificate_key       /etc/ssl/private/tn.key;
    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;
  #securrity Changes-Start
  server_tokens off;
  more_set_headers 'Server: Eff_You_Script_Kiddies!';
  # Securty Changes-End
 # location / {
location @app {
  proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_redirect off;
    proxy_http_version 1.1;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    add_header X-Frame-Options "SAMEORIGIN";
    proxy_set_header Connection '';
    proxy_pass http://puma_tn;
  }

  location ~ ^/(assets|fonts|system)/|favicon.ico|robots.txt {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  underscores_in_headers on;
  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 600;
  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;
}

3 个答案:

答案 0 :(得分:0)

假设您正在将其部署到生产环境,请将以下配置添加到production.rb

config.force_ssl = true

答案 1 :(得分:0)

强制服务器块内的HTTPS连接

if ($scheme != "https") {
  rewrite ^ https://$host$uri permanent;
}

location /块内写

location / {
  return 301 https://$server_name$request_uri;
}

我也认为我们不需要config.force_ssl = true

答案 2 :(得分:0)

我在server ssl块中写了以下内容以使其正常工作。

server {
  listen 443 default_server ssl;
  server_name www.tn.com.au;
  if ($http_x_forwarded_proto = 'http') {
    return 301 https://$server_name$request_uri;   
  }
  .....other configurations
}