Laravel Valet: fetch missing images from production

Devron Baldwin
Apr 10, 2017 · 2 min read

Valet is awesome, developing locally is awesome, having to download all the assets from a live site is not awesome. I’ll show you how you can set up your Valet sites to fetch any missing images from the live server.

Never copy images from live again

Step 1. Secure your local site

Securing your Valet hosted site will also generate an NGINX config file which we can tinker with in a moment.

To secure your local site just cd into the site folder and run valet secure to secure it. See the official Laravel Valet docs for more information.

Step 2. Open the NGINX config file in a text editor

Don’t worry it’s not as scary as it sounds. The config file for your site will be in the valet install folder in your home folder. Open up your terminal of choice and type the following:

cd ~/.valet/Nginx

Now list the contents of the folder with ls and you should see a config file for your site. Lets pretend we’re editing a site in a folder called example.com. Use your favourite text editor to open the config file. I love a bit of Vim so I’d run:

vim example.com.dev

Step 3. Add in the rewrite

Find the line starting error_page 404 and add the following bit of code underneath it. Don’t forget to add in the web address for the production site instead of https://example.com

location ~* \.(png|jpe?g|gif|ico)$ {
expires 24h;
log_not_found off;
try_files $uri $uri/ @production;
}
location @production {
resolver 8.8.8.8;
proxy_pass https://example.com/$uri;
}

Don’t forget to save the file.

Note: Connor helpfully reworked my original code shown above to improve it. I’ve not tested it but it looks good on visual inspection. The code above is my original code and will not check for a local version of the file first before checking the remote server. Check out Connor’s code on his reply.

Step 4. Restart NGINX

Restarting Valet isn’t enough to reload the configuration file we’ve just edited. We have to tell NGINX to reload it’s configuration files with the following command:

sudo nginx -s reload

You’ll need to enter your password to complete the command.

Step 5. Refresh the web page

You should now see the images from the production server.

Head over to the NGINX beginners guide if you’d like to learn more about NGINX configuration.

Update 19th June 2017: if you reinstall Valet you’ll likely lose changes made to the configuration files. If you’re going to reinstall Valet then just make sure you backup the configuration files first.


The original idea for this came from this excellent write up about git workflows for WordPress.

Thanks to Connor for suggesting an alternative version of the code to check locally before checking remote. See his helpful reply.

Devron Baldwin

Written by

Creator of many cups of tea and coffee. I also work as the lead developer at Living DNA.