Search code examples
wordpress.htaccesshttp-redirect

301 redirect if filename end has different characters


The filenames that I want to redirect are like following:

/wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022-3-110.pdf
/wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022-1-510.pdf
/wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022-2-116.pdf

etc.

I want to 301 redirect all that contains the unchanged URL part /wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022- to a file: /wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022a.pdf

I tried this in htaccess without any success:

RewriteRule ^(.+/)DIDUFKU-BLINGSY9-bbteew-hhh-2022-(.*) /wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022a.pdf [R=301,L]

Solution

  • Those files are deleted, those were duplicate files I decided to redirect but not redirecting. I put that rule in htaccess file in WP directory

    If those files are deleted and you put this rule at the end of the .htaccess file, after the WordPress code block then it won't do anything since the request will be routed through WordPress and mostly likely trigger a (WordPress generated) 404 Not Found response.

    This rule needs to go near the top of the .htaccess file, before the WordPress code block. ie. Before the # BEGIN WordPress comment marker.

    However, your rule can be improved (to avoid unnecessary repetition), for example:

    RewriteRule ^(wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022)-[\d-]+\.pdf$ /$1a.pdf
    

    The $1 backreference contains the captured group from the RewriteRule pattern, ie. the string wp-content/uploads/2022/06/DIDUFKU-BLINGSY9-bbteew-hhh-2022.

    You should test first with a 302 (temporary) redirect to avoid potential caching issues.