問題: app error: Missing `secret_token` and `secret_key_base` for 'production' environment, set these values in `config/secrets.yml`
rails的安全機制需要一個秘鑰。在rails 4.x版本的時候, 秘鑰的設置在 RAILS_ROOT/config/secrets.yml, 這文件一般形如:
development: secret_key_base: xxxxxx test: secret_key_base: xxxxxx # Do not keep production secrets in the repository, # instead read values from the environment. production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
在非生產環境下, 秘鑰都是'明文', '硬編碼', 寫在secrets.yml 里面的。這種方式會由於源代碼的泄露, 造成安全問題, 所以這種方式存在安全隱患。
所以rails要求在生產環境下, 通過操作系統的環境變量來設置秘鑰, 這樣相對比較穩妥。
這里可以采取2種方法:
1. 自己動手, 利用linux系統的機制來設置環境變量 SECRET_KEY_BASE = XXX
2. 使用GEM dotenv-deployment幫你設置, 具體機制和方法1本質沒區別。
ps: rails產生秘鑰的指令: rake secret RAILS_ENV=production, 會產生一個秘鑰(好尼瑪長)
這里我選擇方法2, 利用/etc/profile.d/ 下面添加腳本的方式來設置秘鑰:
rake secret RAILS_ENV=production 產生一個秘鑰
在目錄 /etc/profile.d/xxx.sh, 下面新建一個 st_rails_secret_key_env.sh
腳本, 內容: export SECRET_KEY_BASE='你前面產生的那個秘鑰'
然后刷新你的shell, echo $SECRET_KEY_BASE, 輸出成功
extra:
linux下面設置環境變量的方法:
1. 兩個文件都是設置環境變量文件的,/etc/profile是永久性的環境變量,是全局變量,/etc/profile.d/設置所有用戶生效
2. /etc/profile.d/比/etc/profile好維護,不想要什么變量直接刪除/etc/profile.d/下對應的shell腳本即可,不用像/etc/profile需要改動此文件
參考鏈接:
http://stackoverflow.com/questions/23726110/missing-production-secret-key-base-in-rails
http://snakelab.cc/2014/11/08/ror-production.html