public
Last active

How to update WordPress URLs when uploaded images are moved to a CDN

  • Download Gist
sed_change_cdn
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
### Inspiration - http://www.cyberciti.biz/tips/wordpress-cdn-content-delivery-network-configuration.html
 
 
### Replace the following to suit your needs
# domainname(.com) (extension not needed, if .com, .net, .org or .info is used)
# cdn.domainname(.com)
# WordPress database credentials (grep -i db wp-config.php | head -3)
 
 
# Step: 1 - Dump the database
$(which mysqldump) --add-drop-table -u'db_user' -p'db_password' db_name > database.sql
 
 
# Step: 2 - Take a backup to restore the database, if and when something goes wrong!
cp database.sql backup.sql
 
 
# Step: 3 - The actual script
$(which sed) -i -r 's_(?:https?:)?//domainname\.(com|net|org|info)(/wp-content/uploads/[-_/a-zA-Z0-9]+\.)(?ijpg|jpeg|png|gif)_http://cdn.domainname.\1\2\3_g' database.sql
 
 
# Step: 4 - Put the updated database to the live site & pray for things to work. :)
$(which mysql) -u'db_user' -p'db_password' db_name < database.sql
 
 
# step: 5 (optional) - If your prayer wasn't answered...
$(which mysql) -u'db_user' -p'db_password' db_name < backup.sql
 
 
### (Possible) Explanation
# -i to search and replace within the database.sql
# -r to reduce the number of backward slashes (a GNU sed specific extension)
# \1 denotes com, net, org or info (the extension of the domainname
# \2 denotes (/wp-content/uploads/year/month/imagename.)
# \3 denotes jpg, jpeg, png, gif (or their UPPERCASE version)
# ?: denotes non-capturing regex
# ?i denotes case-insensitive regex
# other things are hopefully self-explanatory
 
 
### Limitations
# 1. This will work only if the name of the image contains
# alphanumeric characters and/or hyphen (-) and underscore (_).
# if you have any other characters in the name...
# *please* write it in the comments. I will update the script
# 2. This will work only if the CDN is setup to use cdn.domainname.com
# If the CDN URL differs in some way, then it may need some tweaking
# 3. This script will NOT work, if...
# there is a dot in the name of the image itself (ex: hello.world.png)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.