Search code examples
apache.htaccessmod-rewrite

How to use htaccess to change a folder name and remove a string from the end of a URL


My Goal

I'm trying to use htaccess to change URLs like this...

https://example.com/OLDNAME/item/a-long-file-name-separated-by-hyphens-2

https://example.com/OLDNAME/item/a-long-file-name-separated-by-hyphens

Into URLs like this

https://example.com/NEWNAME/item/a-long-file-name-separated-by-hyphens

The Steps

  1. Replace OLDNAME in the URL with NEWNAME. This rule should execute anytime 'OLDNAME' is found in the URL.

  2. When a URL contains 'OLDNAME', it sometimes has the string '-2' at the end of the URL. If this '-2' string is found, it needs to be removed too.

What I've tried

I have the redirect from OLDNAME to NEWNAME working using this rule...

RewriteRule ^OLDNAME/(.*)$ /NEWNAME/$1 [NC]

I've read many posts and lots of pages from mod_rewrite documentation, but I haven't made much progress trying to remove the -2 yet.

Any help appreciated!


Solution

  • You may use this rule:

    RewriteRule ^OLDNAME/(.+?)(?:-2)?/?$ /NEWNAME/$1 [L,NC,R=302,NE]
    

    I assume you want to redirect to new URL hence added R flag.

    Note pattern in RewriteRule that ends with -2 is outside the capture group. When we use $1 in target it will be without last -2.

    Test Output:

    curl -I 'localhost/OLDNAME/item/a-long-file-name-separated-by-hyphens'
    HTTP/1.1 302 Found
    Date: Fri, 03 Mar 2023 20:48:50 GMT
    Server: Apache/2.4.54 (Unix) OpenSSL/1.1.1s PHP/8.1.12
    Location: http://localhost/NEWNAME/item/a-long-file-name-separated-by-hyphens
    Content-Type: text/html; charset=iso-8859-1
    
    curl -I 'localhost/OLDNAME/item/a-long-file-name-separated-by-hyphens-2'
    HTTP/1.1 302 Found
    Date: Fri, 03 Mar 2023 20:49:53 GMT
    Server: Apache/2.4.54 (Unix) OpenSSL/1.1.1s PHP/8.1.12
    Location: http://localhost/NEWNAME/item/a-long-file-name-separated-by-hyphens
    Content-Type: text/html; charset=iso-8859-1