2

I'm stumped on how to achieve this. The 1-1 redirects work fine as well as the global redirect to send anything to the new page that isn't contained in the code. But when trying to exclude one (or multiple) files/directories it will always redirect to https://example.com/homepage

I ran this through an htaccess checker and when testing against https://test.com/documents/test.pdf it ends right at the exclude statement but on the actual server it does not.

Any ideas?

Use case: https://example.com/documents/test.pdf should not be redirecting, but it does, and it ends up redirecting to https://example.com/homepage.


RewriteEngine on

# Exclude files / directories from redirects

RewriteRule ^(documents)($|/) - [L]

# Redirect specific files / pages to new locations

RedirectMatch 301 /page1.html https://example.com/new-page1.html
RedirectMatch 301 /dir1/page1.html https://example.com/random-new-page.html
RedirectMatch 301 /documents/awesome.pdf https://example.com/new-webpage-to-replacepdf.html

# Redirect anything else that isn't above to the homepage

RedirectMatch 301 / https://example.com/homepage
1

You can't mix RewriteRule and RedirectMatch like that. You need to implement the redirects using another RewriteRule for it to work like you want. A rewrite rule can't prevent a redirect match from working. Instead your rules should be:

RewriteEngine on

# Exclude files / directories from redirects

RewriteRule ^(documents)($|/) - [L]

# Redirect specific files / pages to new locations

RewriteRule ^page1.html$ https://example.com/new-page1.html [R=301,L]
RewriteRule ^dir1/page1.html$ https://example.com/random-new-page.html [R=301,L]
RewriteRule ^documents/awesome.pdf$ https://example.com/new-webpage-to-replacepdf.html [R=301,L]

# Redirect anything else that isn't above to the homepage

RewriteRule .* https://example.com/homepage [R=301,L]

I also would't suggest using that last rule. It isn't good user experience, or good for SEO to redirect everything to the home page. It is better practice to use a rule to direct URL to their exact corresponding counterpart:

RewriteRule (.*) https://example.com/$1 [R=301,L]
  • Thanks for this! – Ghh0st Jun 13 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.