Custom NGINX with Valet

Laravel is cool and Valet is awesome but what if you need to configure custom NGINX configuration for the server you run locally?

Valet is based on NGINX and by installing valet you will automatically install NGINX at /usr/local/etc/nginx here you will find the nginx.conf which is the main global configuration for all the NGINX servers valet is going to use in order to add custom NGINX server, we should first confirm that nginx.conf contains include servers/*; in the http object:


# nginx.conf

http {
	# What ever was here before
	# What ever you wanna change globally 
   	include servers/*;
}

Server file

Now we can enter the servers directory /usr/local/etc/nginx/servers
create a server file e.g. my-server.conf

Domain

Valet also configure the dnsmasq with *.test domains out of the box, and we can easily ride on it. In the custom server configuration file, we would need to configure the port and server_name

FastCGI

fastcgi_pass must use the valet.sock
fastcgi_pass "unix:/Users/YOUR_USER_NAME/.config/valet/valet.sock";

Server file example

server {
	listen 127.0.0.1:80;
	listen [::]:80;
	server_name MY-DOMAIN-NAME.test; ### it has to be .test

	root /Users/my-user/Desktop/projects/example/public; ### absolute pass to the index.php or html

	index  index.php index.html index.htm;

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

	location ~ \.php$ {
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		### fastcgi_pass must use the valet.sock
		### unix:/Users/YOUR_USER_NAME/.config/valet/valet.sock
		fastcgi_pass "unix:/Users/YOUR_USER_NAME/.config/valet/valet.sock";
		fastcgi_index index.php;
		fastcgi_intercept_errors on;
		include fastcgi.conf;
		include fastcgi_params;
		fastcgi_param PATH_INFO $fastcgi_path_info;
		fastcgi_buffers 16 16k;
		fastcgi_buffer_size 32k;
	}

	location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
		expires max;
		log_not_found off;
	}

	error_page  500 502 503 504  /50x.html;
	location = /50x.html {
		root   html;
	}
}

Proxy

Now that everything is working, we can play around and create a proxy configuration:

server {
	# listen  127.0.0.1:80;
	listen 127.0.0.1:80;
	listen [::]:80;
	server_name  proxy-one.test;

	location /dist {
		proxy_pass http://MY-DOMAIN-NAME.test/dist;
	}

	location / {
		proxy_pass http://MY-DOMAIN-NAME.test/;
		proxy_http_version 1.1;
		proxy_set_header X-Forwarded-For $remote_addr;
		proxy_pass_request_headers on;
		proxy_set_header X-Real-IP $remote_addr;
	}
}

Conclusion

Thanks to Valet and few custom configurations, we can create flexible NGINX server configurations locally!