Last active
July 19, 2024 15:37
-
-
Save corbanb/9240622 to your computer and use it in GitHub Desktop.
Nginx redirect assets to CDN from Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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;
}
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
I had tested one of my sites with the above code at Pingdom Website Speed Test. I got a lower score and warnings that I should minimize the amount of redirects. The above code obviously generates a lot of redirects. i wonder, what is the alternative and would rewriting all the paths at my site's HTML/database to the CDN address be a better solution. Is there any speed disadvantage of using Nginx rewrite for this? Thanks.