Skip to content

Instantly share code, notes, and snippets.

@corbanb
Last active July 19, 2024 15:37
Show Gist options
  • Save corbanb/9240622 to your computer and use it in GitHub Desktop.
Save corbanb/9240622 to your computer and use it in GitHub Desktop.
Nginx redirect assets to CDN from Wordpress
server {
## Your website name goes here.
server_name domainname.com www.domainname.com _;
## Your only path reference.
root /var/www/;
listen 8080;
## This should be in your http block and if it is, it's not needed here.
index index.html index.htm index.php;
include conf.d/drop;
location / {
# This is cool because no php is touched for static content
try_files $uri $uri/ /index.php?q=$uri&$args;
}
location ~ \.php$ {
fastcgi_buffers 8 256k;
fastcgi_buffer_size 128k;
fastcgi_intercept_errors on;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/dev/shm/php-fpm-www.sock;
}
location ~ ^(/wp-content/themes|/wp-content/uploads)/.*\.(jpe?g|gif|css|png|js|ico|pdf|m4a|mov|mp3)$ {
rewrite ^ http://cdn.domain.com$request_uri?
permanent;
access_log off;
}
}
@acermez
Copy link

acermez commented Jul 24, 2017

Another way is the "try_files" with proxy, I hope this help anyone looking for a way to use files from production while working at a local environment and big thanks for the author for providing the regex:

# If file not found at local environment, use production server
    location ~ ^(/wp-content/themes|/wp-content/uploads)/.*\.(jpe?g|gif|css|png|js|ico|pdf|m4a|mov|mp3)$ {
        expires 24h;
        log_not_found off;
        try_files $uri $uri/ @production;
    }
    # The Production Server Proxy
    location @production {
        resolver 8.8.8.8;
        proxy_pass https://production.com/$uri;
    }

@audioscavenger
Copy link

hi!
I implemented both these methods with the setting described here: https://github.com/A5hleyRich/wordpress-nginx
Here is the list of extentions I used: (jpe?g|gif|css|png|js|ico|pdf|m4a|mov|mp3|docx?|xlsx?|pptx?)
It works for documents but not for image files. Any idea why I have a GET in the logs for documents (good) and an open() instead of the images?
thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment