Homestead 自定义不同网站的 nginx 配置模板

根据 summber 的描述:

第一次 vagrant up 时,或者执行 vagrant provision 时,虚拟机进入初始化状态;
Vagrant 提供的钩子,触发 『Homestead 脚本』,具体为 homestead.rb
Homestead 脚本读取 Homestead.yaml 文件,对 sites, folders, databases 进行重新初始化;
初始化 sites 时,会读取 Homestead 脚本仓库里带着的 Nginx 站点模板,具体为 serve-laravel.sh
完成初始化。

我们可以找到配置 homestead.yml 文件的时候,sites 除了可以配置 map 和 to 之外,还可以配置一个 type的属性,这个 type 值默认为 laravel。
根据 homestead.rb 中的代码:

settings["sites"].each do |site|

                # Create SSL certificate
                config.vm.provision "shell" do |s|
                    s.name = "Creating Certificate: " + site["map"]
                    s.path = scriptDir + "/create-certificate.sh"
                    s.args = [site["map"]]
                end

                type = site["type"] ||= "laravel"
                ......
                ......
                s.path = scriptDir + "/serve-#{type}.sh"

可以发现根据这个 type 值,是可以动态的加载 nginx 的模板的,只需要以 /serve-#{type}.sh的格式命名。

所以就可以依葫芦画瓢: 新增一个文件 /serve-my.sh:

#!/usr/bin/env bash
declare -A params=$5     # Create an associative array
paramsTXT=""
if [ -n "$5" ]; then
   for element in "${!params[@]}"
   do
      paramsTXT="${paramsTXT}
      fastcgi_param ${element} ${params[$element]};"
   done
fi

block="server {

    listen 80;
    listen [::]:80;

    server_name $1;
    root \"$2\";

    index index.php index.html index.htm;

    rewrite ^/(?!front|views)(.*)$ /index.php?__my=\$1 last;

    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_pass php-upstream;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_split_path_info (.+\.php)(.*)$;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param ENV_VAR_MY local;
    }

    location ~ /\.ht {
        deny all;
    }

    location ~ \.(css|js|icon|png|gif|jpg)$ {
            etag on;
            access_log off;
            add_header Cache-Control public,must-revalidate;
    }
    location =  /robots.txt {
            log_not_found off;
    }
    location =  /favicon.ico {
            log_not_found off;
    }
}
"

echo "$block" > "/etc/nginx/sites-available/$1"
ln -fs "/etc/nginx/sites-available/$1" "/etc/nginx/sites-enabled/$1"
评论数量: 0

0
点赞
908
浏览
0
评论

贡献 69