drexlz0623 2015-11-16 17:48
浏览 47
已采纳

Laravel .env文件中特定于环境的SSL配置

I am running Laravel 5.1 and have multiple environments, some that require SSL, and some that don't. When I require SSL, my config in database.php requires the following in the mysql driver:

'options'   => [
    PDO::MYSQL_ATTR_SSL_KEY     => env('MYSQL_SSL_KEY'), // /path/to/key.pem
    PDO::MYSQL_ATTR_SSL_CERT    => env('MYSQL_SSL_CERT'), // /path/to/cert.pem
    PDO::MYSQL_ATTR_SSL_CA      => env('MYSQL_SSL_CA'), // /path/to/ca.pem
    PDO::MYSQL_ATTR_SSL_CIPHER  => env('MYSQL_SSL_CIPHER')
]

The problem is that when I set these env() vars to null in the environments that don't use SSL (e.g local), it breaks (white screen, etc...). I have to either not set the "options" key or set to to an empty array for it to work, which removes the env() vars which then wouldn't work on the SSL environments.

Is there a way to satisfy this key that works for both SSL and non-SSL environments?

  • 写回答

1条回答 默认 最新

  • duanfei1987 2015-11-16 20:06
    关注

    You can define a new environment variable that enables or disables SSL usage, then use a ternary operator to load the appropriate configuration.

    Add this to your .env file in environments where you need database SSL enabled:

    MYSQL_SSL=true // not having this variable defined or being false, will disable SSL
    

    In your config/database.php file, modify the options key value for your connection to be loaded like this:

    'options' => (env('MYSQL_SSL')) ? [
        PDO::MYSQL_ATTR_SSL_KEY    => env('MYSQL_SSL_KEY'),  // /path/to/key.pem
        PDO::MYSQL_ATTR_SSL_CERT   => env('MYSQL_SSL_CERT'), // /path/to/cert.pem
        PDO::MYSQL_ATTR_SSL_CA     => env('MYSQL_SSL_CA'),   // /path/to/ca.pem
        PDO::MYSQL_ATTR_SSL_CIPHER => env('MYSQL_SSL_CIPHER')
    ] : []
    

    I'm usually against using logic in the configuration files, but this is a case where an exception might be made.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题