How to replace special characters in filenames to fix 404 not found issue in website running on nginx

It is recommended to not include special character in filenames, such as apostrophe(‘), double quote(“), percent(%) etc. Special characters in filenames of the files uploaded to a web server should be avoided for various reasons.

It may cause unexpected behaviour, may cause broken links, 404 not found etc. on different server environments. I today faced an issue with files having apostrophe() in the file name.

I moved one of my websites from Apache server to Nginx server when this issue started to occur. Image files were having (‘) in file name such as south-koreas-presidential-residence.jpg and when I moved it to Nginx server image links started to show 404 not found error.

special character in filenames

When I did ssh to server images files were showing like the following:

How to fix this special character in filenames?

In order to fix this issue there are two steps.

Step 1. Rename strings in the database.

In this step one needs to replace all filename strings containing special character(‘) in the database. Since I was using WordPress I used Search and Replace DB master to replace filenames to remove (‘) with blank space. See image below:

Step 2. Rename filenames to remove spacial character

You can run the following command in ssh terminal to replace special characters in the filenames.

cd folder_containing_files_with_problematic_names
find . -name '*jpg' -exec bash -c ' mv $0 ${0/\turkish-president#U2019s-residence/turkish-presidents-residence}' {} \;

Note: Unicode character(‘) has a code equal to U2019 hence it shows in the filename as shown in the image 2 above.

Leave a Reply