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

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.

    打赏 评论

相关推荐 更多相似问题