首页 > 解决方案 > 使用 Rails 应用程序将 http 重定向到 nginx 中的 https

问题描述

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

下面是我的 nginx 配置文件。

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;
}

标签: ruby-on-railsnginx

解决方案


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

config.force_ssl = true

推荐阅读