Skip to content

Instantly share code, notes, and snippets.

@ramonchito2
Last active September 26, 2017 20:17
Show Gist options
  • Save ramonchito2/eef394636513b1a8a933d16ed0b9f0e1 to your computer and use it in GitHub Desktop.
Save ramonchito2/eef394636513b1a8a933d16ed0b9f0e1 to your computer and use it in GitHub Desktop.
Nginx location rules for fallback images from live (Homestead)

Dynamically update nginx config files for each site on provision so location rules aren't lost.

When using Laravel's Homestead, one thing that can be a pain is having to constantly re-add configuration rules in your site's nginx config upon provisioning. This is infinitely worse when you have to configure multiple sites 😤 . However with this setup, you can put those days behind you. The following instructions focus on location, however this can be applied to pretty much anything.

The location rule here pulls images from your live site if they don't exist on your local dev environment. Helps reduce GBs of unnecessary assets on your local machine In order for the following code to work, your site folder must have the same name as the live site.

Edit Homestead's default nginx config shell script

  • Inside of the ~/Homestead/scripts folder, edit "serve-laravel.sh".

  • Insert the accompaning code in its respective places.

  • That's it!

Alternatively...

  • Inside of the aforementioned scripts folder, make a copy the "server-laravel.sh" file and name it "serve-custom.sh".

  • Insert the accompaning code in its respective places.

  • Edit your Homestead.yaml and add a "type" property of "custom" inside of the site configuration area.

sites:
    - map: yoursite.dev
      to: /home/vagrant/Code/yoursite
      type: custom
  • FYI, type can be whatever you want it to be named, as long as "serve-{type}.sh" exists in the scripts folder. If not, defaults to "serve-laravel.sh".

Note: If your Homestead local repository is updated/changed to a new tag, there should be no merge conflicts if the alternative way is implemented.

#--------------------
# ADD THE FOLLOWING ABOVE (OUTSIDE OF) SERVER BLOCK
#--------------------
# Extract Site Name
re="(old.|new.)?(.+).dev";
sitename="somethingwentwrong.org";
if [[ $1 =~ $re ]]; then
sitename=${BASH_REMATCH[2]}
fi
#-------------------
# ADD THE FOLLOWING INSIDE OF SERVER BLOCK
# ABOVE DEFAULT LOCATION RULES
#-------------------
# the following can also be statically placed in
# /etc/nginx/sites-available/(sitename), just
# unescape $url by removing '\' and replace $sitename.org
location ~* ^.+\.(svg|svgz|jpg|jpeg|gif|png|ico|bmp)$ {
try_files \$uri @image_fallback;
}
location @image_fallback {
proxy_pass http://$sitename.org;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment