1

I am trying to remove 2 folders path from the URL but I cant get that to work. My URL looks like this: http://example.com/files/uploads/PP/test.pdf I would like to remove the /files/uploads from the URL so that I remain only with http://example.com/PP/test.pdf.

My Rewrite rule looks like this:

RewriteBase /files/uploads/
RewriteRule ^files/uploads/(.*) /$1 [NC,L,R=302]

The URL gets rewrited in http://example.com/PP/test.pdf but it says that the file does not exist. How can I do fix this?

SirSeba
  • 151
  • 8

1 Answers1

1

You don't use .htaccess to actually "change" the URL. You use .htaccess to allow the "changed" URL to work. The URL must first be changed in your internal links (in your HTML source).

(Aside: You can later implement an additional redirect to redirect the "old" URL to the "new" URL - for the benefit of SEO - but that is secondary and not required to get this to "work". And since this is a .pdf file then that may not be a concern anyway. This is what you are trying to do with the "redirect" you have posted.)

So, asssuming the actual file is located at /files/uploads/PP/test.pdf and you are linking to /PP/test.pdf (the new canonical URL) then you would use the following at the top of the root .htaccess file to internally rewrite requests from /PP/test.pdf back to /files/uploads/PP/test.pdf:

RewriteEngine On

RewriteRule ^PP/test\.pdf$ files/uploads/$0 [END]

Where $0 is a backrefence that contains the entire match from the RewriteRule pattern. ie. PP/test.pdf in this case.

To match any .pdf URL that is one path-segment deep (ie. /<path-segment>/<file>.pdf) then modify the RewriteRule pattern accordingly. For example:

RewriteRule ^[^/]+/[^/]+\.pdf$ files/uploads/$0 [END]

Reference:

MrWhite
  • 43,179
  • 8
  • 60
  • 84
  • Thank you @MrWhite. For the past 2 days I was trying to get that to work and couldn't understand why it wasnt working. For my usecase is SEO not relevant but thanks for the tip. – SirSeba Apr 04 '23 at 12:21