When we start a new symfony/laravel/{enter random framework here} project there are two tasks we need to do first. Create a new vhost, and add new entry in /etc/hosts. Today i'm trying to implement a little nginx trick to eliminate the first task.
I'm not sure dynamic
is the right word in the title, But i can't find a more suitable word. I'll create a generic nginx vhost/config that'll serve all symfony project.
Create a new file in nginx config directory, Ex: /etc/nginx/conf.d/symfony.conf
Put the following config in it. Be sure to reload/restart nginx afterwards.
server {
listen 80;
server_name ~^(?<project_name>[^\.]*)\.(?<env>prod|dev)$;
set $app "app.php";
if ($env = "dev" ) {
set $app "app_dev.php";
}
root /Users/sarim/Sites/php55/$project_name/web;
index $app index.html index.htm;
location / {
try_files $uri $uri/ /$app?$args;
}
location ~ ^/(app|app_dev|config)\.php(/|$) {
fastcgi_pass unix:/usr/local/var/run/php55.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
Put your php-fpm address in fastcgi_pass
. You'll also need to edit the /Users/sarim/Sites/php55
part. Thats where i put my php framework projects. Now lets assume you have a project named matrix
in that folder. Now go ahead and add following lines into /etc/hosts
127.0.0.1 matrix.dev matrix.prod
Now open http://matrix.dev/ and http://matrix.prod/ in your browser. You should see the matrix
project in dev and prod mode. Try any other project in that folder. It'll work
So whats happening here ? the magic is in the server_name line. A little bit of regex that matches anything but dot, goes into project_name
variable. And prod
or dev
after the dot, goes env
variable. After that we set app
variable to app.php
assuming our environment is prod. But if env == dev, it sets to app_dev.php
. This app
variable is used later to set which front controller we send user request to.
PS: You can further automate the process by installing a intelligent DNS server and configure it to send .*dev|prod
requests to 127.0.0.1
.
Happy Coding.